Moving all vowels to the end of string using JavaScript

In JavaScript, you can move all vowels to the end of a string while maintaining the relative positions of consonants. This is useful for text processing and string manipulation tasks.

Problem

We need to write a JavaScript function that takes a string and constructs a new string where all consonants maintain their relative positions and all vowels are moved to the end.

Approach

The solution involves iterating through the string, separating vowels and consonants into different variables, then concatenating them with consonants first and vowels at the end.

Example

const str = 'sample string';
const moveVowels = (str = '') => {
    const vowels = 'aeiou';
    let front = '';
    let rear = '';
    
    for(let i = 0; i 

smpl strngaei 
Hll Wrldeo o
JvScrtpaai

Enhanced Version with Case Handling

Here's an improved version that handles both uppercase and lowercase vowels:

const moveVowelsAdvanced = (str = '') => {
    const vowels = 'aeiouAEIOU';
    let consonants = '';
    let vowelsPart = '';
    
    for(const char of str) {
        if(vowels.includes(char)) {
            vowelsPart += char;
        } else {
            consonants += char;
        }
    }
    
    return consonants + vowelsPart;
};

console.log(moveVowelsAdvanced('Hello World'));
console.log(moveVowelsAdvanced('JAVASCRIPT'));
console.log(moveVowelsAdvanced('Programming'));
Hll Wrldeo o
JVSCRPTAAI
PrgrmmngoeAi

Using Array Methods

Alternative approach using array methods for a more functional programming style:

const moveVowelsArray = (str = '') => {
    const vowels = 'aeiouAEIOU';
    const chars = str.split('');
    
    const consonants = chars.filter(char => !vowels.includes(char));
    const vowelChars = chars.filter(char => vowels.includes(char));
    
    return consonants.join('') + vowelChars.join('');
};

console.log(moveVowelsArray('tutorial'));
console.log(moveVowelsArray('point'));
ttrlauoi
pntoi

Key Points

  • The algorithm maintains the relative order of consonants and vowels separately
  • Consider case sensitivity when checking for vowels
  • Spaces and special characters are treated as consonants
  • Time complexity is O(n) where n is the string length

Conclusion

Moving vowels to the end of a string is efficiently achieved by separating characters into consonants and vowels during iteration, then concatenating them in the desired order. This technique is useful for various text processing applications.

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

387 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements