2015-04-04 56 views
4

我使用基本的JavaScript来计算字符串中元音的数量。下面的代码工作,但我想清理一下。考虑到它是一个字符串,会不会使用.includes()?如果可能的话清理条件语句,我想使用类似string.includes("a", "e", "i", "o", "u")的东西。另外,是否需要将输入转换为字符串?使用JavaScript计算字符串中元音的数量

function getVowels(str) { 
    var vowelsCount = 0; 

    //turn the input into a string 
    var string = str.toString(); 

    //loop through the string 
    for (var i = 0; i <= string.length - 1; i++) { 

    //if a vowel, add to vowel count 
    if (string.charAt(i) == "a" || string.charAt(i) == "e" || string.charAt(i) == "i" || string.charAt(i) == "o" || string.charAt(i) == "u") { 
     vowelsCount += 1; 
    } 
    } 
    return vowelsCount; 
} 

回答

13

实际上,你可以用一个小的正则表达式做到这一点:

function getVowels(str) { 
    var m = str.match(/[aeiou]/gi); 
    return m === null ? 0 : m.length; 
} 

这只是对正则表达式匹配(g使得搜索整个字符串,i使得它不区分大小写),并返回数字的比赛。我们检查null有没有匹配(即没有元音),并在这种情况下返回0。

3
function countVowels(subject) { 
    return subject.match(/[aeiou]/gi).length; 
} 

你不需要转换任何东西,如果需要的话,Javascript的错误处理足以提示你这么简单的功能。

+1

当'subject'不包含任何元音时它不起作用。 – 2016-11-22 13:02:43

+0

'return(subject.match(/ [aeiou]/gi)|| [])。length;'为了以防万一 – maximast 2017-06-01 19:35:14

2

转换字符串使用Array.from()方法的阵列,然后使用Array.prototype.filter()方法到阵列过滤仅包含元音,然后length属性将包含元音的数量。

const countVowels = str => Array.from(str) 
 
    .filter(letter => 'aeiou'.includes(letter)).length; 
 

 
console.log(countVowels('abcdefghijklmnopqrstuvwxyz')); // 5 
 
console.log(countVowels('test')); // 1 
 
console.log(countVowels('ddd')); // 0

1

使用match但如果没有找到匹配

const countVowels = (subject => (subject.match(/[aeiou]/gi) || []).length); 
0

只要使用此功能[对于ES5]要小心,因为它可以返回一个

function countVowels(str){ 
    return (str.match(/[aeiou]/gi) == null) ? 0 : str.match(/[aeiou]/gi).length;   
} 

会像一个魅力

0

count = function(a) { 
 
    //var a=document.getElementById("t"); 
 
    console.log(a); //to see input string on console 
 
    n = a.length; 
 
    console.log(n); //calculated length of string 
 
    var c = 0; 
 
    for (i = 0; i < n; i++) { 
 
    if ((a[i] == "a") || (a[i] == "e") || (a[i] == "i") || (a[i] == "o") || (a[i] == "u")) { 
 
     console.log(a[i]); //just to verify 
 
     c += 1; 
 
    } 
 
    } 
 

 
    document.getElementById("p").innerText = c; 
 
}
<p>count of vowels </p> 
 
<p id="p"></p> 
 
<input id="t" /> 
 
<input type="button" value="count" onclick="count(t.value)" />

0

这也使用.replace()方法通过更换任何不以空字符串元音(基本上就会删除这些字符)并返回来解决新的字符串长度:

function vowelCount(str) { 
    return str.replace(/[^aeiou]/gi, "").length; 
}; 

或者如果你喜欢ES6

const vowelCount = (str) => (str.replace(/[^aeiou]/gi,"").length)