我们需要编写一个JavaScript函数,该函数将字符串作为输入,并且仅反转字符串的元音。
例如-
如果输入字符串是-
const str = 'Hello';
那么输出应该是-
const output = 'Holle';
为此的代码将是-
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));
控制台中的输出将是-
Holle