有人可以阐明一种方法,将字符串中出现的所有元音与字符“i”交换。
对于用户输入“Hello world!”、“Hilli wird!”应该被退回。
下面的方法只能删除元音,而不是用选定的字符替换它们。 我不想使用字符串替换。我必须采取更费力的方法来操作数组。
function withoutVowels(string) {
var withoutVowels = "";
for (var i = 0; i < string.length; i++) {
if (!isVowel(string[i])) {
withoutVowels += string[i];
}
}
return withoutVowels;
}
function isVowel(char) {
return 'aeiou'.includes(char);
}
console.log(withoutVowels('Hello World!'));
最佳答案
不使用字符串替换,而是使用 RegExp :)
function withoutVowels(string, replaceWith) {
return string.split(/[aeiou]/).join(replaceWith)
}
console.log(withoutVowels('Hello World!', 'i'));
关于javascript - 如何用字符替换字符串中的所有元音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60240207/