我正在写一个代码来去掉单词中的最后一个元音,但它删除了最后一个字母.我哪里错了

I am writing a code to get rid of the last vowel in a word, but it is deleting the last letter. Where am I going wrong?

本文关键字:最后一个 错了 删除 单词中 代码 一个      更新时间:2023-09-26

我正在写一个代码来去掉单词中的最后一个元音,但它正在删除最后一个字母。我哪里错了?

 function removeLastVowel(word) {
      var vowels = ["a", 'e', 'i', 'o', 'u'];
      for (var i = word.length - 1; i >= 0; i--) {
        if (vowels.indexOf(word[i]) !== undefined) {
          return (word.slice(0, i) + word.slice(i + 1));
          }
        }
      return word;
    }
console.log(removeLastVowel("heard"));

indexOf()如果未找到,则返回-1,而不是未定义的

这个问题已经有了答案,但我发现用regex解决这个问题很有趣。

这可能看起来很粗糙,但它确实有效;)

这个正则表达式只是说:
如果之后没有这些[aeiou],则服用其中一种/aeiou]。我花了一点时间才明白这一点

function removeLastVowel(word) {
  return word.replace(/[aeiou](?!.*?[aeiou])/i, '')
}
console.log(removeLastVowel("ax"));
console.log(removeLastVowel("aa"));
console.log(removeLastVowel("hearaa"));
console.log(removeLastVowel("heara"));
console.log(removeLastVowel("hea"));

相关文章: