I want a function that I can go from A to B, B to C, Z to A.
My function is currently like so:
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');
It works for A to X, but when I use Z... it goes to [ instead of A.
I want a function that I can go from A to B, B to C, Z to A.
My function is currently like so:
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');
It works for A to X, but when I use Z... it goes to [ instead of A.
Share Improve this question asked Mar 29, 2017 at 13:56 RolandoRolando 62.6k103 gold badges278 silver badges422 bronze badges 4- 1 You need to manually check for Z. You are increasing ASCII value here. – user1481317 Commented Mar 29, 2017 at 13:58
- 1 Can't you just check for 'A'? Just specify the end limit and wrap it back if it exceeds it. – Carcigenicate Commented Mar 29, 2017 at 13:58
- @BibekSubedi Actually, it's the UTF-16 code unit value not the ASCII value. – Tom Blodget Commented Mar 29, 2017 at 16:34
- I notice in your description you refer to 'A' to 'Z'. But in your example, you use 'a'. Those are different letter characters (as are 'ā', 'ą', …). JavaScript doesn't have the built-in concept of Letter but Unicode does and all characters in JavaScript are Unicode. You can build a regular expression for all letters here. – Tom Blodget Commented Mar 29, 2017 at 16:38
4 Answers
Reset to default 6You could use parseInt
with radix
36 and the opposite method Number#toString
with the same radix, and a correction for the value.
function nextChar(c) {
var i = (parseInt(c, 36) + 1 ) % 36;
return (!i * 10 + i).toString(36);
}
console.log(nextChar('a'));
console.log(nextChar('z'));
Simple condition.
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');
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
function nextChar(c) {
return String.fromCharCode(((c.charCodeAt(0) + 1 - 65) % 25) + 65);
}
where 65 stands for offset from 0 in ASCII table and 25 means that after 25th character it will start from the beginning (offset character code is divided by 25 and you get remainder that is offset back to proper ASCII code)