【问题标题】:What is a method that can be used to increment letters?有什么方法可以用来增加字母?
【发布时间】:2012-09-12 07:30:22
【问题描述】:

有人知道提供增加字母的方法的 Javascript 库(例如下划线、jQuery、MooTools 等)吗?

我希望能够做类似的事情:

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

【问题讨论】:

  • 我不确定您要查找的语法是否可行,但可以通过方法进行操作。
  • 应用是什么?

标签: javascript increment alphabetical


【解决方案1】:

简单直接的解决方案

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

正如其他人所指出的,缺点是它可能无法按预期处理字母“z”之类的情况。但这取决于你想从中得到什么。上面的解决方案将为 'z' 之后的字符返回 '{',这是 ASCII 中 'z' 之后的字符,因此它可能是您正在寻找的结果,具体取决于您的用例。


独特的字符串生成器

(2019 年 5 月 9 日更新)

由于此答案已获得如此广泛的关注,因此我决定将其扩展至原始问题的范围之外,以潜在地帮助那些在 Google 上遇到此问题的人。

我发现我经常想要的是在某个字符集中生成顺序的、唯一的字符串(例如只使用字母),所以我更新了这个答案,在此处包含一个可以做到这一点的类:

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'

【讨论】:

  • 简单的解决方案,但不处理'z'或'Z'的出现。
  • 一种嗡嗡声,它将进入特殊字符,如 /
  • 正是我正在寻找的东西,因为我试图通过旧式 IBM Code Page 437 字体挑选不显示的 unicode 字符。你真的为我节省了几个小时的字符输入时间。
  • Daniel Thompson 这个解决方案提供了足够多的信息,您可以自己处理极端情况。毕竟,这是一个“互相帮助”的网站,而不是免费的网站。
  • 我花了一段时间才弄清楚如何将起始字符作为参数。我最终使用了 ._nextId = [chars.split('').findIndex(x=>x==start)];或者 start+1 如果你想让它比你传入的多 1 开始。
【解决方案2】:

纯 javascript 应该可以解决问题:

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

【讨论】:

  • Pure Charm ,任何关于避免空格和特殊字符的建议。 coderByte 对此有疑问
【解决方案3】:

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

nextChar('yz'); // 返回“ZA”

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

【讨论】:

  • 已将 if (same(u,'Z')){ 更改为 if (u == 'Z'){ 并且效果很好,谢谢!
  • 很高兴它的工作,并感谢您的反馈。也许最初的错误是因为标题为same(str,char) 的函数没有粘贴在那里?我不知道。
  • 一定是这样,same() 显然是一个自定义函数。哦,好吧,== 有效,如果我想非常确定,我可以使用===,但我已经测试过了,没问题。再次感谢!
  • 如果你输入 zz 你会得到三个 A 是不是代码中的错误??
  • 我不这么认为? zz 之后是什么?对吗?我没有在这台机器上安装 excel(仔细检查),但对我来说听起来不错。
【解决方案4】:

一种可能的方式如下定义

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

【讨论】:

    【解决方案5】:

    你可以试试这个

    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

    【讨论】:

    • 嗯。需要更多 jQuery。
    【解决方案6】:

    我需要多次使用字母序列,所以我根据这个 SO question 制作了这个函数。我希望这可以帮助其他人。

    function charLoop(from, to, callback)
    {
        var i = from.charCodeAt(0);
        var to = to.charCodeAt(0);
        for(;i<=to;i++) callback(String.fromCharCode(i));
    }
    
    • 来自 - 首字母
    • 到 - 最后一个字母
    • callback(letter) - 函数为每个字母执行 顺序

    使用方法:

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

    See this working demo

    【讨论】:

      【解决方案7】:

      添加所有这些答案:

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

      【讨论】:

        【解决方案8】:

        这个效果不错:

        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'
        

        【讨论】:

          【解决方案9】:

          一个只是为了笑的解决方案

          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"));

          【讨论】:

            【解决方案10】:

            这真的很老了。但我需要这个功能,而且没有一个解决方案最适合我的用例。我想生成 a, b, c...z, aa,ab...zz, aaa... 。这个简单的递归完成了这项工作。

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

            【讨论】:

              【解决方案11】:

              在闭包中使用 {a: 'b', b: 'c', etc} 创建一个函数:-

              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')
              

              添加大写和数字:-

              let nextCh = (
                  (alphabeta, s) => (
                      [alphabeta, alphabeta.toUpperCase(), "01234567890"]
                          .forEach(chars => chars.split('')
                             .reduce((a,b) => (s[a]=b, b))), 
                      c=> s[c] 
                  )
              )("abcdefghijklmopqrstuvwxyza", {});
              

              附言在某些版本的 Javascript 中,您可以使用 [...chars] 代替 chars.split('')

              【解决方案12】:

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

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

              底部的输入代码和查找的编解码器位于顶部(即输出代码与输入代码相同,但移位了 1)。该函数只更改字母,即如果传入任何其他字符,它将被此编解码器更改。

              【讨论】:

                【解决方案13】:
                
                function charLoop(from, to, callback) {
                    var i = from.charCodeAt(0);
                    var to = to.charCodeAt(0);
                    for (; i <= to; i++) {
                        callback(String.fromCharCode(i));
                    }
                }
                
                var sequence = "";
                charLoop("A", "Z", function (char) {
                    sequence += char + " ";
                });
                
                sequence = sequence.trim();
                sequence = sequence.split(" ");
                
                var resseq = sequence;
                var res = "";
                var prevlet = "";
                var nextlet = "";
                
                for (b = 0; b < resseq.length; b++) {
                    if (prevlet != "") {
                        prevlet = resseq[b];
                    }
                
                    for (a = 0; a < sequence.length; a++) {
                        for (j = 1; j < 100; j++) {
                            if (prevlet == "") {
                                prevlet = sequence[a];
                                nextlet = sequence[a + 1];
                                res += sequence[a] + sequence[a] + 0 + j + " ";
                            }
                            else {
                
                                if (j < 10) {
                                    res += prevlet + sequence[a] + 0 + j + " ";
                                }
                                else {
                                    res += prevlet + sequence[a] + j + " ";
                                }
                            }
                        }
                    }
                }
                
                document.body.innerHTML = res;
                
                

                【讨论】:

                • 您可能想解释一下您在这里做了什么以及它如何提供帮助,而不仅仅是一段代码,谢谢! - 也许代码中有一些有用的注释?
                • String.fromCharCode() 它返回字母的字符代码。
                【解决方案14】:

                基于@Nathan wall 答案递增和递减

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

                【讨论】:

                  【解决方案15】:

                  这是我在 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
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2020-04-30
                    • 1970-01-01
                    • 2020-07-31
                    • 2012-01-27
                    • 2010-10-27
                    相关资源
                    最近更新 更多