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
Swapping letter with succeeding alphabet in 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';
Output
Then the output should be ?
const output = 'ipx bsf zpv'
Therefore, let's write the code for this function ?
How It Works
The algorithm converts each alphabetic character to its next letter in the alphabet. For 'z' and 'Z', it wraps around to 'a' and 'A' respectively. Non-alphabetic characters remain unchanged.
Example
The code for this will be ?
const str = 'how are you';
const isAlpha = code => (code >= 65 && code = 97 && 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));
ipx bsf zpv
Code Breakdown
The function uses three helper functions:
- isAlpha() - Checks if character code is alphabetic (A-Z or a-z)
- isLast() - Identifies 'Z' (90) and 'z' (122) for wraparound
- nextLetterString() - Main function that processes each character
Alternative Approach
Here's a simpler version using regular expressions:
const nextLetterSimple = str => {
return str.replace(/[a-zA-Z]/g, char => {
if (char === 'z') return 'a';
if (char === 'Z') return 'A';
return String.fromCharCode(char.charCodeAt(0) + 1);
});
};
console.log(nextLetterSimple('how are you'));
console.log(nextLetterSimple('xyz ABC'));
ipx bsf zpv yza BCD
Conclusion
Both approaches successfully swap each letter with its succeeding alphabet character. The regex version is more concise, while the reduce method offers more control over the transformation process.
