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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2256607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:29:46  来源:igfitidea点击:

How to get the next letter of the alphabet in Javascript?

javascriptjqueryjquery-uiautocompletecouchdb

提问by Dominic Barnes

I am build an autocomplete that searches off of a CouchDB View.

我正在构建一个从 CouchDB 视图中搜索的自动完成功能。

I need to be able to take the final character of the input string, and replace the last character with the next letter of the english alphabet. (No need for i18n here)

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

For Example:

例如:

  • Input String= "b"
  • startkey= "b"
  • endkey= "c"
  • 输入字符串= "b"
  • 开始键= "b"
  • 结束键= "c"

OR

或者

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

(in case you're wondering, I'm making sure to include the option inclusive_end=falseso that this extra character doesn't taint my resultset)

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



The Question

问题

  • Is there a function natively in Javascript that can just get the next letter of the alphabet?
  • Or will I just need to suck it up and do my own fancy function with a base string like "abc...xyz" and indexOf()?
  • Javascript 中是否有本机函数可以获取字母表的下一个字母?
  • 或者我只需要把它吸起来并用像“abc...xyz”这样的基本字符串来做我自己的花哨的功能indexOf()

回答by icktoofay

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

回答by kennebec

// This will return A for Z and a for z.

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

回答by kumarharsh

A more comprehensive solution, which gets the next letter according to how MS Excel numbers it's columns... A B C ... Y Z AA AB ... AZ BA ... ZZ AAA

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

This works with small letters, but you can easily extend it for caps too.

这适用于小写字母,但您也可以轻松地将其扩展为大写字母。

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

回答by mbl

Here is a function that does the same thing (except for upper case only, but that's easy to change) but uses sliceonly once and is iterative rather than recursive. In a quick benchmark, it's about 4 times faster (which is only relevant if you make really heavy use of it!).

这是一个做同样事情的函数(除了大写,但很容易改变)但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

}

}

回答by Mahan Mashoof

Just to explain the main part of the code that Bipul Yadav wrote (can't comment yet due to lack of reps). Without considering the loop, and just taking the char "a" as an example:

只是为了解释 Bipul Yadav 编写的代码的主要部分(由于缺乏代表,还不能发表评论)。不考虑循环,仅以字符“a”为例:

"a".charCodeAt(0) = 97...hence "a".charCodeAt(0) + 1 = 98and String.fromCharCode(98) = "b"...so the following function for any letter will return the next letter in the alphabet:

"a".charCodeAt(0) = 97...因此"a".charCodeAt(0) + 1 = 98String.fromCharCode(98) = "b"...因此对于任何字母的以下函数将返回字母表中的下一个字母:

function nextLetterInAlphabet(letter) {
  if (letter == "z") {
    return "a";
  } else if (letter == "Z") {
    return "A";
  } else {
    return String.fromCharCode(letter.charCodeAt(0) + 1);
  }
}

回答by Bipul Yadav

var input = "Hello";
var result = ""
for(var i=0;i<input.length;i++)
{
  var curr = String.fromCharCode(input.charCodeAt(i)+1);
  result = result +curr;
}
console.log(result);