Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Change every letter to next letter - JavaScript
We are required to write a JavaScript function that takes in a string and changes every letter of the string from the English alphabets to its succeeding element.
For example: If the string is ?
const str = 'how are you';
Then the output should be ?
const output = 'ipx bsf zpv';
How It Works
The algorithm processes each character by checking if it's a letter using ASCII codes. For letters 'a-y' and 'A-Y', it moves to the next letter. For 'z' and 'Z', it wraps around to 'a' and 'A' respectively. Non-alphabetic characters remain unchanged.
Example
Following is the code ?
const str = 'how are you';
const isAlpha = code => (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
const isLast = code => code === 90 || code === 122;
const nextLetterString = str => {
const strArr = str.split('');
return strArr.reduce((acc, val) => {
const code = val.charCodeAt(0);
if(!isAlpha(code)){
return acc+val;
};
if(isLast(code)){
return acc+String.fromCharCode(code-25);
};
return acc+String.fromCharCode(code+1);
}, '');
};
console.log(nextLetterString(str));
Output
Following is the output in the console ?
ipx bsf zpv
Key Points
- ASCII codes: 'A-Z' are 65-90, 'a-z' are 97-122
- Wrap-around: 'z' becomes 'a', 'Z' becomes 'A'
- Non-letters preserved: Spaces and punctuation remain unchanged
Alternative Approach Using String Methods
const nextLetterStringSimple = str => {
return str.split('').map(char => {
if (/[a-y]/i.test(char)) {
return String.fromCharCode(char.charCodeAt(0) + 1);
} else if (char === 'z') {
return 'a';
} else if (char === 'Z') {
return 'A';
}
return char;
}).join('');
};
console.log(nextLetterStringSimple('xyz ABC'));
yza BCD
Conclusion
This function effectively shifts each letter to the next in the alphabet using ASCII manipulation. The wrap-around logic ensures 'z' becomes 'a' and 'Z' becomes 'A' for complete alphabet cycling.
