什么是可用于增加字母的方法?

时间:2012-09-19 22:57:30

标签: javascript increment alphabetical

有没有人知道Javascript库(例如下划线,jQuery,MooTools等)提供了一种递增字母的方法?

我希望能够做到这样的事情:

"a"++; // would return "b"

15 个答案:

答案 0 :(得分:143)

简单直接的解决方案

function nextChar(c) {
    return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');

正如其他人所指出的,缺点是它可能无法像预期的那样处理字母'z'之类的情况。但这取决于你想要的东西。上面的解决方案将在'z'之后为字符返回'{',这是ASCII中'z'之后的字符,因此它可能是您要查找的结果,具体取决于您的用例。


唯一字符串生成器

(2019/05/09更新)

由于这个答案已经获得了如此多的关注度,我决定将其扩展到原始问题的范围之外,以便潜在地帮助那些从谷歌那里绊脚石的人。

我发现我经常想要的东西会在某个字符集中生成顺序的,唯一的字符串(例如只使用字母),所以我已经更新了这个答案,以包含一个将在此处执行此操作的类: / p>

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'

答案 1 :(得分:42)

普通的javascript应该可以解决问题:

String.fromCharCode('A'.charCodeAt() + 1) // Returns B

答案 2 :(得分:19)

如果给定的字母是z怎么办?这是一个更好的解决方案。它包括A,B,C ...... X,Y,Z,AA,AB,......等。它基本上会增加字母,就像Excel电子表格的列ID一样。

nextChar(&#39; YZ&#39); //返回&#34; ZA&#34;

&#13;
&#13;
    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);
});
&#13;
<input id="entry" type="text"></input>
<button id="btn">enter</button>
&#13;
&#13;
&#13;

答案 3 :(得分:4)

你可以试试这个

console.log( 'a'.charCodeAt​(0))​

首先将其转换为Ascii数字..递增它..然后从Ascii转换为char ..

var nex = 'a'.charCodeAt(0);
console.log(nex)
$('#btn1').on('click', function() {
   var curr = String.fromCharCode(nex++)
   console.log(curr)
});

检查FIDDLE

答案 4 :(得分:4)

我需要多次使用字母序列,所以我根据这个SO问题做了这个功能。我希望这可以帮助别人。

function charLoop(from, to, callback)
{
    var i = from.charCodeAt(0);
    var to = to.charCodeAt(0);
    for(;i<=to;i++) callback(String.fromCharCode(i));
}
  • 来自 - 开始信
  • 最后一封信
  • 回调(字母) - 为每个字母执行的函数 序列

如何使用它:

charLoop("A", "K", function(char) {
    //char is one letter of the sequence
});

<强> See this working demo

答案 5 :(得分:3)

添加所有这些答案:

// 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);
}

示例:http://jsfiddle.net/pitaj/3F5Qt/

答案 6 :(得分:2)

一种可能的方法如下所述

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 ...

答案 7 :(得分:1)

这个确实运作良好:

var nextLetter = letter => {
    let charCode = letter.charCodeAt(0);
    let isCapital = letter == letter.toUpperCase();

    if (isCapital == true) {
        return String.fromCharCode((charCode - 64) % 26 + 65)
    } else {
        return String.fromCharCode((charCode - 96) % 26 + 97)
    }
}

EXAMPLES

nextLetter("a"); // returns 'b'
nextLetter("z"); // returns 'a'
nextLetter("A"); // returns 'B'
nextLetter("Z"); // returns 'A'

答案 8 :(得分:1)

一个只为笑的解决方案

function nextLetter(str) {
  const Alphabet = [
    // lower case alphabet
    "a", "b", "c",
    "d", "e", "f",
    "g", "h", "i",
    "j", "k", "l",
    "m", "n", "o",
    "p", "q", "r",
    "s", "t", "u",
    "v", "w", "x",
    "y", "z",
    // upper case alphabet
    "A", "B", "C",
    "D", "E", "F",
    "G", "H", "I",
    "J", "K", "L",
    "M", "N", "O",
    "P", "Q", "R",
    "S", "T", "U",
    "V", "W", "X",
    "Y", "Z"
  ];

  const LetterArray = str.split("").map(letter => {
    if (Alphabet.includes(letter) === true) {
      return Alphabet[Alphabet.indexOf(letter) + 1];
    } else {
      return " ";
    }
  });

  const Assemble = () => LetterArray.join("").trim();
  return Assemble();
}


console.log(nextLetter("hello*3"));

答案 9 :(得分:0)

This is really old. But I needed this functionality and none of the solutions are optimal for my use case. I wanted to generate a, b, c...z, aa,ab...zz, aaa... . This simple recursion does the job.

function nextChar(str) {
if (str.length == 0) {
    return 'a';
}
var charA = str.split('');
if (charA[charA.length - 1] === 'z') {
    return nextID(str.substring(0, charA.length - 1)) + 'a';
} else {
    return str.substring(0, charA.length - 1) +
        String.fromCharCode(charA[charA.length - 1].charCodeAt(0) + 1);
}
};

答案 10 :(得分:0)

在闭包中使用{a:'b',b:'c'等}来创建函数:-

String

用法:-

let nextChar = (s => (
    "abcdefghijklmopqrstuvwxyza".split('')
    .reduce((a,b)=> (s[a]=b, b)), // make the lookup
c=> s[c] // the function returned
))({}); // parameter s, starts empty

添加大写字母和数字:-

nextChar('a')

p.s。在某些版本的Javascript中,您可以使用let nextCh = ( (alphabeta, s) => ( [alphabeta, alphabeta.toUpperCase(), "01234567890"] .forEach(chars => chars.split('') .reduce((a,b) => (s[a]=b, b))), c=> s[c] ) )("abcdefghijklmopqrstuvwxyza", {}); 代替[...chars]

答案 11 :(得分:0)

这是我在https://stackoverflow.com/a/28490254/881441上提交的rot13算法的变体:

function rot1(s) {
  return s.replace(/[A-Z]/gi, c =>
    "BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza"[
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(c) ] )
}

输入代码位于底部,查找的编解码器位于顶部(即,输出代码与输入代码相同,但移位了1)。该功能仅更改字母,即,如果传入任何其他字符,此编解码器将保持不变。

答案 12 :(得分:0)

PyTorch>0.4.0

答案 13 :(得分:0)

基于@Nathan墙的答案增量和减量

// 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();

答案 14 :(得分:0)

这是我在Javascript中将增量字母增加到无穷大的函数(仅限大写)

function getNextStringId(str) {
    let index = str.length-1;
    let baseCode= str.charCodeAt(index);
    do{
        baseCode= str.charCodeAt(index);
        let strArr= str.split("");
        if(strArr[index] == "Z"){
            strArr[index] = "A";
            if(index==0){
                strArr.unshift("A");
            }
        }
        else{
            strArr[index]= String.fromCharCode(baseCode + 1);
        }
        str= strArr.join("");
        index--;
    } while(baseCode == 90)
    return str;
}


getNextStringId("A") // B
getNextStringId("Z") // AA
getNextStringId("ABZZ") // ACAA