使用JavaScript计算字符串中元音的数量 [英] Counting number of vowels in a string with JavaScript
问题描述
我正在使用基本的JavaScript来计算字符串中元音的数量。下面的代码工作,但我想清理一下。考虑到它是一个字符串,会使用 .includes()
帮助吗?我想使用像 string.includes(a,e,i,o,u)
这样的东西,如果可能的话条件陈述。此外,是否需要将输入转换为字符串?
I'm using basic JavaScript to count the number of vowels in a string. The below code works but I would like to have it cleaned up a bit. Would using .includes()
help at all considering it is a string? I would like to use something like string.includes("a", "e", "i", "o", "u")
if at all possible to clean up the conditional statement. Also, is it needed to convert the input into a string?
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;
}
推荐答案
你实际上可以用一个小的正则表达式:
You can actually do this with a small regex:
function getVowels(str) {
var m = str.match(/[aeiou]/gi);
return m === null ? 0 : m.length;
}
这只是与正则表达式匹配( g
使其搜索整个字符串, i
使其不区分大小写)并返回匹配数。我们检查 null
如果没有匹配(即没有元音),则在这种情况下返回0。
This just matches against the regex (g
makes it search the whole string, i
makes it case-insensitive) and returns the number of matches. We check for null
incase there are no matches (ie no vowels), and return 0 in that case.
这篇关于使用JavaScript计算字符串中元音的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!