Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reversing vowels in a string JavaScript
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
Advertisements