文字をインクリメントする方法を提供するJavascriptライブラリ(アンダースコア、jQuery、MooToolsなど)を知っている人はいますか?
私は次のようなことができるようになりたいです:
"a"++; // would return "b"
文字をインクリメントする方法を提供するJavascriptライブラリ(アンダースコア、jQuery、MooToolsなど)を知っている人はいますか?
私は次のようなことができるようになりたいです:
"a"++; // would return "b"
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');
他の人が指摘しているように、欠点は、文字「z」のようなケースを期待どおりに処理できない可能性があることです。しかし、それはあなたがそれから何を望んでいるかに依存します。上記のソリューションは、「z」の後の文字に対して「{」を返します。これは、ASCIIの「z」の後の文字であるため、ユースケースによっては、探している結果になる可能性があります。
(2019/05/09更新)
この回答は非常に多くの人に知られているので、元の質問の範囲を少し超えて、Googleからこれに遭遇している人々を助ける可能性があるように拡張することにしました。
私がよく欲しいのは、特定の文字セット(文字のみを使用するなど)で連続した一意の文字列を生成するものであることがわかったので、この回答を更新して、ここでそれを行うクラスを含めました。
class StringIdGenerator {
constructor(chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
this._chars = chars;
this._nextId = [0];
}
next() {
const r = [];
for (const char of this._nextId) {
r.unshift(this._chars[char]);
}
this._increment();
return r.join('');
}
_increment() {
for (let i = 0; i < this._nextId.length; i++) {
const val = ++this._nextId[i];
if (val >= this._chars.length) {
this._nextId[i] = 0;
} else {
return;
}
}
this._nextId.push(0);
}
*[Symbol.iterator]() {
while (true) {
yield this.next();
}
}
}
使用法:
const ids = new StringIdGenerator();
ids.next(); // 'a'
ids.next(); // 'b'
ids.next(); // 'c'
// ...
ids.next(); // 'z'
ids.next(); // 'A'
ids.next(); // 'B'
// ...
ids.next(); // 'Z'
ids.next(); // 'aa'
ids.next(); // 'ab'
ids.next(); // 'ac'
プレーンなJavaScriptでうまくいくはずです。
String.fromCharCode('A'.charCodeAt() + 1) // Returns B
与えられた文字がzの場合はどうなりますか? これがより良い解決策です。A、B、C... X、Y、Z、AA、AB などになります。基本的には、Excel スプレッドシートの列 ID のように文字を増やします。
nextChar('yz'); // "ZA" を返す
function nextChar(c) {
var u = c.toUpperCase();
if (same(u,'Z')){
var txt = '';
var i = u.length;
while (i--) {
txt += 'A';
}
return (txt+'A');
} else {
var p = "";
var q = "";
if(u.length > 1){
p = u.substring(0, u.length - 1);
q = String.fromCharCode(p.slice(-1).charCodeAt(0));
}
var l = u.slice(-1).charCodeAt(0);
var z = nextLetter(l);
if(z==='A'){
return p.slice(0,-1) + nextLetter(q.slice(-1).charCodeAt(0)) + z;
} else {
return p + z;
}
}
}
function nextLetter(l){
if(l<90){
return String.fromCharCode(l + 1);
}
else{
return 'A';
}
}
function same(str,char){
var i = str.length;
while (i--) {
if (str[i]!==char){
return false;
}
}
return true;
}
// below is simply for the html sample interface and is unrelated to the javascript solution
var btn = document.getElementById('btn');
var entry = document.getElementById('entry');
var node = document.createElement("div");
node.id = "node";
btn.addEventListener("click", function(){
node.innerHTML = '';
var textnode = document.createTextNode(nextChar(entry.value));
node.appendChild(textnode);
document.body.appendChild(node);
});
<input id="entry" type="text"></input>
<button id="btn">enter</button>
考えられる方法の 1 つは、以下に定義されているとおりです。
function incrementString(value) {
let carry = 1;
let res = '';
for (let i = value.length - 1; i >= 0; i--) {
let char = value.toUpperCase().charCodeAt(i);
char += carry;
if (char > 90) {
char = 65;
carry = 1;
} else {
carry = 0;
}
res = String.fromCharCode(char) + res;
if (!carry) {
res = value.substring(0, i) + res;
break;
}
}
if (carry) {
res = 'A' + res;
}
return res;
}
console.info(incrementString('AAA')); // will print AAB
console.info(incrementString('AZA')); // will print AZB
console.info(incrementString('AZ')); // will print BA
console.info(incrementString('AZZ')); // will print BAA
console.info(incrementString('ABZZ')); // will print ACAA
console.info(incrementString('BA')); // will print BB
console.info(incrementString('BAB')); // will print BAC
// ... and so on ...
あなたはこれを試すことができます
console.log( 'a'.charCodeAt(0))
最初にそれをアスキー番号に変換します..それをインクリメントします..次にアスキーから文字に変換します..
var nex = 'a'.charCodeAt(0);
console.log(nex)
$('#btn1').on('click', function() {
var curr = String.fromCharCode(nex++)
console.log(curr)
});
FIDDLEを確認してください
これらすべての回答に追加します。
// first code on page
String.prototype.nextChar = function(i) {
var n = i | 1;
return String.fromCharCode(this.charCodeAt(0) + n);
}
String.prototype.prevChar = function(i) {
var n = i | 1;
return String.fromCharCode(this.charCodeAt(0) - n);
}
@Nathan wall 回答の増分と減分に基づく
// Albhabet auto increment and decrement
class StringIdGenerator {
constructor(chars = '') {
this._chars = chars;
}
next() {
var u = this._chars.toUpperCase();
if (this._same(u,'Z')){
var txt = '';
var i = u.length;
while (i--) {
txt += 'A';
}
this._chars = txt+'A';
return (txt+'A');
} else {
var p = "";
var q = "";
if(u.length > 1){
p = u.substring(0, u.length - 1);
q = String.fromCharCode(p.slice(-1).charCodeAt(0));
}
var l = u.slice(-1).charCodeAt(0);
var z = this._nextLetter(l);
if(z==='A'){
this._chars = p.slice(0,-1) + this._nextLetter(q.slice(-1).charCodeAt(0)) + z;
return p.slice(0,-1) + this._nextLetter(q.slice(-1).charCodeAt(0)) + z;
} else {
this._chars = p+z;
return p + z;
}
}
}
prev() {
var u = this._chars.toUpperCase();
console.log("u "+u)
var l = u.slice(-1).charCodeAt(0);
var z = this._nextLetter(l);
var rl = u.slice(1)
var y = (rl == "A") ? "Z" :this._prevLetter(rl.charCodeAt(0))
var txt = '';
var i = u.length;
var j = this._chars
var change = false
while (i--) {
if(change){
if (u[u.length-1] == "A"){
txt += this._prevLetter(u[i].charCodeAt(0))
}else{
txt += u[i]
}
}else{
if (u[u.length-1] == "A"){
txt += this._prevLetter(u[i].charCodeAt(0))
change = true
}else{
change = true
txt += this._prevLetter(u[i].charCodeAt(0))
}
}
}
if(u == "A" && txt == "Z"){
this._chars = ''
}else{
this._chars = this._reverseString(txt);
}
console.log(this._chars)
return (j);
}
_reverseString(str) {
return str.split("").reverse().join("");
}
_nextLetter(l){
if(l<90){
return String.fromCharCode(l + 1);
}
else{
return 'A';
}
}
_prevLetter(l){
if(l<=90){
if(l == 65) l = 91
return String.fromCharCode(l-1);
}
else{
return 'A';
}
}
_same(str,char){
var i = str.length;
while (i--) {
if (str[i]!==char){
return false;
}
}
return true;
}
}
使用法
const ids = new StringIdGenerator();
ids.next();
ids.prev();