We are required to write a JavaScript function that takes a string as input and reverse only the vowels of a string.
For example −
If the input string is −
const str = 'Hello';
Then the output should be −
const output = 'Holle';
The code for this will be −
const str = 'Hello'; const reverseVowels = (str = '') => { const vowels = new Set(['a','e','i','o','u','A','E','I','O','U']); let left = 0, right = str.length-1; let foundLeft = false, foundRight = false; str = str.split(""); while(left < right){ if(vowels.has(str[left])){ foundLeft = true }; if(vowels.has(str[right])){ foundRight = true }; if(foundLeft && foundRight){ [str[left],str[right]] = [str[right],str[left]]; foundLeft = false; foundRight = false; }; if(!foundLeft) { left++ }; if(!foundRight) { right-- }; }; return str.join(""); }; console.log(reverseVowels(str));
And the output in the console will be −
Holle