反转字符串 JavaScript 中的元音
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 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