문자열을 입력으로 받아 문자열의 모음만 반전시키는 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