【问题标题】:How to increment letters in javascript to next letter?如何将javascript中的字母增加到下一个字母?
【发布时间】:2017-08-23 01:34:35
【问题描述】:

我想要一个可以从 A 到 B、B 到 C、Z 到 A 的函数。

我的功能目前是这样的:

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

它适用于 A 到 X,但是当我使用 Z... 时它转到 [ 而不是 A。

【问题讨论】:

  • 您需要手动检查 Z。您在此处增加 ASCII 值。
  • 你不能只检查'A'吗?只需指定结束限制,如果超过则将其包装回来。
  • @BibekSubedi 实际上,它是 UTF-16 代码单元值而不是 ASCII 值。
  • 我注意到您在描述中提到了“A”到“Z”。但在您的示例中,您使用“a”。这些是不同的字母字符('ā','ą',......)。 JavaScript 没有内置的 Letter 概念,但 Unicode 有,而且 JavaScript 中的所有字符都是 Unicode。您可以为所有字母 here 构建正则表达式。

标签: javascript


【解决方案1】:

简单的条件。

function nextChar(c) {
    var res = c == 'z' ? 'a' : c == 'Z' ? 'A' : String.fromCharCode(c.charCodeAt(0) + 1);
    console.log(res);
}
nextChar('Z');
nextChar('z');
nextChar('a');

【讨论】:

    【解决方案2】:

    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);
            }
        });
    }
    
    console.log("nextLetter('z'): ", nextLetter('z'));
    
    console.log("nextLetter('Z'): ", nextLetter('Z'));
    
    console.log("nextLetter('x'): ", nextLetter('x'));

    Reference

    【讨论】:

      【解决方案3】:

      您可以使用 parseIntradix 36 以及相反的方法 Number#toString 使用相同的基数,并修正值。

      function nextChar(c) {
          var i = (parseInt(c, 36) + 1 ) % 36;
          return (!i * 10 + i).toString(36);
      }
      
      console.log(nextChar('a'));
      console.log(nextChar('z'));

      【讨论】:

      • @Gary,基本上它会检查i 的值,然后你会得到零:0 -> 1 * 10 + 0 => 10 或例如2020 -> 0 * 10 + 20 => 20。或者简而言之,如果它不为零,则取值;如果为零,则取值 10。 10 的值是字母 'a''z' 的值为 35。通过加一并取余数,你得到零。从零值开始,您需要得到'a'。这就是为什么你需要10 的值。 (! 是一个逻辑 NOT 运算符,返回 truefalse。通过乘法将值转换为数字,如 01。)
      【解决方案4】:
      function nextChar(c) {
              return String.fromCharCode(((c.charCodeAt(0) + 1 - 65) % 25) + 65);
      }
      

      其中 65 表示 ASCII 表中从 0 开始的偏移量,25 表示在第 25 个字符之后它将从头开始(偏移字符代码除以 25 并且您得到的余数偏移回正确的 ASCII 代码)

      【讨论】:

        猜你喜欢
        • 2015-11-16
        • 2011-01-16
        • 1970-01-01
        • 1970-01-01
        • 2012-05-05
        • 1970-01-01
        • 1970-01-01
        • 2019-03-31
        • 1970-01-01
        相关资源
        最近更新 更多