2017-03-29 141 views
1

我想我可以从A到B,B到C,Z到A的功能如何将javascript中的字母增加到下一个字母?

我的功能目前像这样:

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

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

+1

您需要手动检查Z.您在此处增加ASCII值。 –

+1

你不能只检查'A'吗?只需指定结束限制,并在超过结束限制时将其换回。 – Carcigenicate

+0

@BibekSubedi实际上,它是UTF-16代码单元值而不是ASCII值。 –

回答

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

+0

你能详细说明一下'!i'的用法吗,我不确定那里发生了什么... – Gary

+0

@Gary,基本上它检查'i'的值,你得到零:'0 - > 1 * 10 + 0 => 10'或者例如'20':'20→0 * 10 + 20 => 20'。或者简而言之,如果它不是零或10,如果它是零,则取值。 “10”的值是字母“a”。 “z”的值是“35”。通过加上一个并取其余部分,就可以得到零。从零值开始,你需要得到''''。这就是为什么你需要'10'的价值。 ('!'是一个逻辑NOT运算符,并且返回'true'或'false',通过将该值与数字相乘,例如'0'或'1'。 –

+0

感谢您的深度回复,凉! – Gary

2

简单的条件。

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

2
function nextChar(c) { 
     return String.fromCharCode((c.charCodeAt(0) + 1 - 65) % 25) + 65); 
} 

,其中65名代表从ASCII表0-25偏移意味着25字符后,将从头开始(偏移字符代码由25分,你会得到余数是偏移回适当的ASCII码)

相关问题