如何在 JavaScript 中检查元音?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5488028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:23:48  来源:igfitidea点击:

How do I check for vowels in JavaScript?

javascriptregex

提问by Max

I'm supposed to write a function that takes a character (i.e. a string of length 1) and returns true if it is a vowel, false otherwise. I came up with two functions, but don't know which one is better performing and which way I should prefer. The one with RegEx is way simpler but I am unsure whether I should try to avoid using RegEx or not?

我应该编写一个函数,它接受一个字符(即长度为 1 的字符串),如果它是元音则返回 true,否则返回 false。我想出了两个功能,但不知道哪个性能更好,我应该更喜欢哪种方式。使用 RegEx 的方式更简单,但我不确定是否应该尽量避免使用 RegEx?

Without RegEx:

没有正则表达式:

function isVowel(char) {
  if (char.length == 1) {
    var vowels = new Array("a", "e", "i", "o", "u");
    var isVowel = false;

    for (e in vowels) {
      if (vowels[e] == char) {
        isVowel = true;
      }
    }

    return isVowel;
  }
}

With RegEx:

使用正则表达式:

function isVowelRegEx(char) {
  if (char.length == 1) {
    return /[aeiou]/.test(char);
  }
}

回答by Raynos

benchmark

基准

I think you can safely say a for loop is faster.

我认为您可以安全地说 for 循环更快。

I do admit that a regexp looks cleaner in terms of code. If it's a real bottleneck then use a for loop, otherwise stick with the regular expression for reasons of "elegance"

我承认正则表达式在代码方面看起来更清晰。如果这是一个真正的瓶颈,则使用 for 循环,否则出于“优雅”的原因坚持使用正则表达式

If you want to go for simplicity then just use

如果你想简单,那么只需使用

function isVowel(c) {
    return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1
}

回答by RobG

Lots of answers available, speed is irrelevant for such small functions unless you are calling them a few hundred thousand times in a short period of time. For me, a regular expression is best, but keep it in a closure so you don't build it every time:

有很多可用的答案,速度对于这样的小函数来说无关紧要,除非您在短时间内调用它们几十万次。对我来说,正则表达式是最好的,但把它放在一个闭包中,这样你就不会每次都构建它:

Simple version:

简单版:

function vowelTest(s) {
  return (/^[aeiou]$/i).test(s);
}

More efficient version:

更高效的版本:

var vowelTest = (function() {
  var re = /^[aeiou]$/i;
  return function(s) {
    return re.test(s);
  }
})();

Returns trueif sis a single vowel (upper or lower case) and falsefor everything else.

返回trueifs是单个元音(大写或小写)和false其他所有内容。

回答by Emmerman

cycles, arrays, regexp... for what? It can be much quicker :)

循环、数组、正则表达式……为了什么?它可以更快:)

function isVowel(char)
{
    return char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u' || false;
}

回答by Buhake Sindi

This is a rough RegExp function I would have come up with (it's untested)

这是我想出的一个粗略的 RegExp 函数(未经测试)

function isVowel(char) {
    return /^[aeiou]$/.test(char.toLowerCase());
}

Which means, if (char.length == 1 && 'aeiou' is contained in char.toLowerCase()) then return true.

这意味着,if (char.length == 1 && 'aeiou' is contained in char.toLowerCase()) then return true

回答by José Salgado

function findVowels(str) {
  return str.match(/[aeiou]/ig);
}

findVowels('abracadabra'); // 'aaaaa'

Basically it returns all the vowels in a given string.

基本上它返回给定字符串中的所有元音。

回答by cwallenpoole

Personally, I would define it this way:

就个人而言,我会这样定义:

function isVowel( chr ){ return 'aeiou'.indexOf( chr[0].toLowerCase() ) !== -1 }

You could also use ['a','e','i','o','u']and skip the length test, but then you are creating an array each time you call the function. (There are ways of mimicking this via closures, but those are a bit obscure to read)

您也可以使用['a','e','i','o','u']并跳过长度测试,但是每次调用该函数时都会创建一个数组。(有一些方法可以通过闭包来模仿这一点,但这些方法读起来有点难懂)

回答by H?vard

function isVowel(char)
{
  if (char.length == 1)
  {
    var vowels = "aeiou";
    var isVowel = vowels.indexOf(char) >= 0 ? true : false;

    return isVowel;
  }
}

Basically it checks for the index of the character in the string of vowels. If it is a consonant, and not in the string, indexOfwill return -1.

基本上它会检查元音字符串中字符的索引。如果是辅音,并且不在字符串中,indexOf则返回 -1。

回答by Intellidroid

I kind of like this method which I think covers all the bases:

我有点喜欢这种方法,我认为它涵盖了所有基础:

const matches = str.match(/aeiou/gi];
return matches ? matches.length : 0;

回答by Penny Liu

I created a simplified version using Array.prototype.includes(). My technique is similar to @Kunle Babatunde.

我使用Array.prototype.includes()创建了一个简化版本。我的技术类似于@Kunle Babatunde

const isVowel = (char) => ["a", "e", "i", "o", "u"].includes(char);

console.log(isVowel("o"), isVowel("s"));

回答by Kunle Babatunde

  //function to find vowel
const vowel = (str)=>{
  //these are vowels we want to check for
  const check = ['a','e','i','o','u'];
  //keep track of vowels
  var count = 0;
  for(let char of str.toLowerCase())
  {
    //check if each character in string is in vowel array
    if(check.includes(char)) count++;
  }
  return count;
}

console.log(vowel("hello there"));