Moving all vowels to the end of string using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string. Our function should construct a new string in which all the consonants should hold their relative position and all the vowels should be pushed to the end of string.

Example

Following is the code −

 Live Demo

const str = 'sample string';
const moveVowels = (str = '') => {
   const vowels = 'aeiou';
   let front = '';
   let rear = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(vowels.includes(el)){
         rear += el;
      }else{
         front += el;
      };
   };
   return front + rear;
};
console.log(moveVowels(str));

Output

smpl strngaei
raja
Updated on 19-Apr-2021 11:21:22

Advertisements