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

我正在构建一个自动填充function,可以搜索CouchDB View。

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

例如:

  • 输入字符串 =“b”
  • startkey =“b”
  • endkey =“c”

要么

  • 输入字符串 =“foo”
  • startkey =“foo”
  • endkey =“fop”

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


问题

  • Javascript中是否存在一个可以获取下一个字母表字母的函数?
  • 或者我是否只需要使用像“abc … xyz”和indexOf()这样的基本字符串来完成自己的花哨function?

 my_string.substring(0,my_string.length-1)+String.fromCharCode(my_string.charCodeAt(my_string.length-1)+1) 

//这将返回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); } }); } 

一个更全面的解决方案,根据MS Excel如何编号的列获得下一个字母… ABC ... YZ 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; }; 

这是一个执行相同操作的函数(仅限大写,但这很容易更改)但只使用一次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 

}