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
Program to make vowels in string uppercase and change letters to next letter in alphabet (i.e. z->a) in JavaScript
We need to write a JavaScript function that takes a string and performs two transformations: convert vowels to uppercase and shift each letter to the next letter in the alphabet (with 'z' wrapping to 'a').
The function should construct a new string based on the input string where all vowels are uppercased and each alphabet character moves to the next letter in sequence.
Problem Understanding
For example, if the input string is:
const str = 'newString';
The expected output should be:
const output = 'oExSusIoh';
Here's how the transformation works:
- 'n' ? 'o' (next letter)
- 'e' ? 'E' (vowel, so uppercase and move to next: 'f' ? 'E')
- 'w' ? 'x' (next letter)
- 'S' ? 'S' (stays same as it's uppercase)
- 'u' ? 'U' (vowel, uppercase)
Solution
const str = 'newString';
const capitalizeAndMove = (str = '') => {
let result = '';
result = str.replace(/[a-z]/g, function(c) {
// Check if character is a vowel
if ('aeiou'.indexOf(c) > -1) {
// For vowels: move to next letter and make uppercase
let nextChar = String.fromCharCode(c.charCodeAt(0) + 1);
if (nextChar > 'z') nextChar = 'a'; // Handle 'z' wrap-around
return nextChar.toUpperCase();
} else {
// For consonants: just move to next letter
let nextChar = c.charCodeAt(0) + 1;
return String.fromCharCode(nextChar > 122 ? 97 : nextChar);
}
});
return result;
};
console.log(capitalizeAndMove(str));
oFxTusjoh
Alternative Approach
Here's a more concise version using the same logic:
const str = 'newString';
const capitalizeAndMove = (str = '') => {
return str.replace(/[a-z]/g, function(c) {
const isVowel = 'aeiou'.indexOf(c) > -1;
const nextCharCode = (c.charCodeAt(0) - 97 + 1) % 26 + 97;
const nextChar = String.fromCharCode(nextCharCode);
return isVowel ? nextChar.toUpperCase() : nextChar;
});
};
console.log(capitalizeAndMove(str));
oFxTusjoh
How It Works
The function uses a regular expression /[a-z]/g to match all lowercase letters. For each matched character:
- Check if it's a vowel using
'aeiou'.indexOf(c) > -1 - Calculate the next character using
charCodeAt()andString.fromCharCode() - Handle the wrap-around case where 'z' becomes 'a' using modulo operation
- Convert to uppercase if it's a vowel
Conclusion
This solution efficiently transforms strings by shifting letters and capitalizing vowels using regular expressions and character code manipulation. The modulo operation ensures proper wrap-around from 'z' to 'a'.
