如何在Javascript中获取下一个字母表的字母?

Dom*_*nes 30 javascript jquery couchdb jquery-ui autocomplete

我正在构建一个自动填充功能,可以搜索CouchDB View.

我需要能够获取输入字符串的最后一个字符,并将最后一个字符替换为英文字母的下一个字母.(这里不需要i18​​n)

例如:

  • 输入字符串 ="b"
  • startkey ="b"
  • endkey ="c"

要么

  • 输入字符串 ="foo"
  • startkey ="foo"
  • endkey ="fop"

(如果你想知道,我确保包含该选项,inclusive_end=false以便这个额外的字符不会污染我的结果集)


问题

  • Javascript中是否存在一个可以获取下一个字母表字母的函数?
  • 或者我只需要吸吮它并使用像"abc ... xyz"这样的基本字符串来执行我自己的花哨功能indexOf()

ick*_*fay 45

my_string.substring(0, my_string.length - 1)
      + String.fromCharCode(my_string.charCodeAt(my_string.length - 1) + 1)
Run Code Online (Sandbox Code Playgroud)

  • 但要注意z/Z`z +1 = {`和`Z +1 = [`的边缘情况 (6认同)

ken*_*bec 26

//这将返回A代表Z和a代表z.

function nextLetter(s){
    return s.replace(/([a-zA-Z])[^a-zA-Z]*$/, function(a){
        var c= a.charCodeAt(0);
        switch(c){
            case 90: return 'A';
            case 122: return 'a';
            default: return String.fromCharCode(++c);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)


kum*_*rsh 15

一个更全面的解决方案,根据MS Excel如何编号列,得到下一个字母... A B C ... Y Z AA AB ... AZ BA ... ZZ AAA

这适用于小写字母,但您也可以轻松扩展它.

getNextKey = function(key) {
  if (key === 'Z' || key === 'z') {
    return String.fromCharCode(key.charCodeAt() - 25) + String.fromCharCode(key.charCodeAt() - 25); // AA or aa
  } else {
    var lastChar = key.slice(-1);
    var sub = key.slice(0, -1);
    if (lastChar === 'Z' || lastChar === 'z') {
      // If a string of length > 1 ends in Z/z,
      // increment the string (excluding the last Z/z) recursively,
      // and append A/a (depending on casing) to it
      return getNextKey(sub) + String.fromCharCode(lastChar.charCodeAt() - 25);
    } else {
      // (take till last char) append with (increment last char)
      return sub + String.fromCharCode(lastChar.charCodeAt() + 1);
    }
  }
  return key;
};
Run Code Online (Sandbox Code Playgroud)


小智 5

这是一个功能相同的函数(仅大写字母除外,但很容易更改),但slice仅使用一次,并且是迭代的,而不是递归的。在一个快速的基准测试中,它的速度提高了约4倍(仅在您真正使用它的情况下才有意义!)。

function nextString(str) {
    if (! str)
        return 'A'  // return 'A' if str is empty or null

    let tail = ''
    let i = str.length -1
    let char = str[i]
    // find the index of the first character from the right that is not a 'Z'
    while (char === 'Z' && i > 0) {
        i--
        char = str[i]
        tail = 'A' + tail   // tail contains a string of 'A'
    }
    if (char === 'Z')   // the string was made only of 'Z'
        return 'AA' + tail
    // increment the character that was not a 'Z'
    return str.slice(0, i) + String.fromCharCode(char.charCodeAt(0) + 1) + tail
Run Code Online (Sandbox Code Playgroud)

}