Reverse Vowels of a string

by raviteja gunda

HTML

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.

 

Example 1:

Input: s = "hello"
Output: "holle"
Example 2:

Input: s = "leetcode"
Output: "leotcede"

JavaScript

function reverseVowels(s: string): string {
    let length = s.length;
    let splitString = s.split('');
    let vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
    for(let i = 0, j = length - 1; i < j; ) {
        if(!vowels.includes(splitString[i])) {
            i++;
        }
        if(!vowels.includes(splitString[j])) {
            j--;
        }
        if(vowels.includes(splitString[i]) && vowels.includes(splitString[j])) {
            let temp = splitString[i];
            splitString[i] = splitString[j];
            splitString[j] = temp;
            i++;
            j--;
        }
    }
    return splitString.join('');
};

//top
most of them used similar approach so saving this regex sol
function reverseVowels(s: string): string {
    const vow = s.match(/[aeiou]/ig);
    return s.replace(/[aeiou]/ig, el=> vow.pop());
};