Reversing consonants only from a string in JavaScript


Problem

We are required to write a JavaScript function that takes in a string of lowercase english alphabets as the only argument.

The function should construct a new string in which the order of consonants is reversed and the vowels hold their relative positions.

For example, if the input to the function is −

const str = 'somestring';

Then the output should be −

const output = 'gomenrtiss';

Example

The code for this will be −

const str = 'somestring';
const reverseConsonants = (str = '') => {
   const arr = str.split("");
   let i = 0, j = arr.length - 1;
   const consonants = 'bcdfghjklnpqrstvwxyz';
   while(i < j){
      while(i < j && consonants.indexOf(arr[i]) < 0) {
         i++;
      }
      while(i< j && consonants.indexOf(arr[j]) < 0) {
         j--;
      }
      let tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
      i++;
      j--;
   }
   let result = "";
   for(let i = 0; i < arr.length; i++) {
      result += arr[i];
   }
   return result;
};
console.log(reverseConsonants(str));

Output

And the output in the console will be −

gomenrtiss

Updated on: 19-Mar-2021

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements