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

后端 未结 7 981
醉酒成梦
醉酒成梦 2021-01-03 18:20

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

I need to be able to take the final character of the input string, and replace the last character wit

7条回答
  •  清酒与你
    2021-01-03 18:46

    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

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

提交回复
热议问题