Moving vowels and consonants using JavaScript



Problem

We are required to write a JavaScript function that takes in a string of English alphabets. Our function should construct a new string and every consonant should be pushed forward 9 places through the alphabet. If they pass 'z', start again at 'a'. And every vowel should be pushed by 5 places.

Example

Following is the code −

 Live Demo

const str = 'sample string'; const moveWords = (str = '') => {    str = str.toLowerCase();    const legend = 'abcdefghijklmnopqrstuvwxyz';    const isVowel = char => 'aeiou'.includes(char);    const isAlpha = char => legend.includes(char);    let res = '';    for(let i = 0; i < str.length; i++){       const el = str[i];       if(!isAlpha(el)){          res += el;          continue;       };       let pos;       const ind = legend.indexOf(el);       if(isVowel(el)){          pos = (21 + ind) % 26;       }else{          pos = (ind + 9) % 26;       };       res += legend[pos];    };    return res; }; console.log(moveWords(str));

Output

bvvyuz bcadwp
Updated on: 2021-04-17T12:58:15+05:30

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements