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:

  1. Check if it's a vowel using 'aeiou'.indexOf(c) > -1
  2. Calculate the next character using charCodeAt() and String.fromCharCode()
  3. Handle the wrap-around case where 'z' becomes 'a' using modulo operation
  4. 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'.

Updated on: 2026-03-15T23:19:00+05:30

581 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements