Bear in mind that characters sets are reasonable sensible: 'a' is less than 'b', which is less that 'c', and so on up to 'z'. And the same applies for the uppercase letters as well: 'A' < 'B' < 'C' ... < 'Z'
So, you can write a conditional that filters to just lowercase alphabetic characters like this:
if (charCode >= 'a' && charCode <='z')
Then ... it gets nasty. Javascript is a weakly (or poorly if you prefer) typed language - which means in this case that the type of variable changes depending on what you do with it.
So adding on to a character doesn't return a character - it returns a pair of characters: "x" + 1 == "x1" as the addition is assumed to be string concatenation. That why your code uses charCodeAt rather than
charAt
- but you need to convert it back when you try to build a string using string.fromCharCode:
let result = "";
str = "12Hello34";
for(let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i);
if (charCode >= 65 && charCode <= 90 ) {
if (charCode == 90) charCode = 65;
else charCode = charCode + 1;
}
else if (charCode >= 97 && charCode <= 122 ) {
if (charCode == 122) charCode = 97;
else charCode = charCode + 1;
}
result += String.fromCharCode(charCode);
}
console.log (result);