2017-03-29 140 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碼)

相關問題