使用 JavaScript 计算字符串中元音的数量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29450399/
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
Counting number of vowels in a string with JavaScript
提问by dcook
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?
我正在使用基本的 JavaScript 来计算字符串中元音的数量。下面的代码有效,但我想把它清理一下。.includes()考虑到它是一个字符串,会使用帮助吗?我想使用类似string.includes("a", "e", "i", "o", "u")if 的东西来清理条件语句。另外,是否需要将输入转换为字符串?
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;
}
回答by James Thorpe
You can actually do this with a small regex:
你实际上可以用一个小的正则表达式来做到这一点:
function getVowels(str) {
var m = str.match(/[aeiou]/gi);
return m === null ? 0 : m.length;
}
This just matches against the regex (gmakes it search the whole string, imakes it case-insensitive) and returns the number of matches. We check for nullincase there are no matches (ie no vowels), and return 0 in that case.
这只是匹配正则表达式(g使其搜索整个字符串,i使其不区分大小写)并返回匹配数。我们检查nullincase 是否没有匹配(即没有元音),并在这种情况下返回 0。
回答by Micha? Per?akowski
Convert the string to an array using the Array.from()method, then use the Array.prototype.filter()method to filter the array to contain only vowels, and then the lengthproperty will contain the number of vowels.
使用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
回答by sudo
function countVowels(subject) {
return subject.match(/[aeiou]/gi).length;
}
You don't need to convert anything, Javascript's error handling is enough to hint you on such a simple function if it will be needed.
您不需要转换任何东西,如果需要,Javascript 的错误处理足以提示您使用这样一个简单的函数。
回答by Sumer
Short and ES6, you can use the function count(str);
短而 ES6,你可以使用函数 count(str);
const count = str => (str.match(/[aeiou]/gi) || []).length;
回答by Grant Miller
You can convert the given string into an array using the spread operator, and then you can filter()the characters to only those which are vowels (case-insensitive).
您可以使用扩展运算符将给定的字符串转换为数组,然后您可以filter()将字符转换为元音(不区分大小写)。
Afterwards, you can check the lengthof the array to obtain the total number of vowels in the string:
之后,您可以检查length数组的 以获取字符串中元音的总数:
const vowel_count = string => [...string].filter(c => 'aeiou'.includes(c.toLowerCase())).length;
console.log(vowel_count('aaaa')); // 4
console.log(vowel_count('AAAA')); // 4
console.log(vowel_count('foo BAR baz QUX')); // 5
console.log(vowel_count('Hello, world!')); // 3
回答by Carmine Tambascia
As the introduction of forEach in ES5 this could be achieved in a functional approach, in a more compact way, and also have the count for each vowel and store that count in an Object.
随着 ES5 中 forEach 的引入,这可以通过函数方法以更紧凑的方式实现,并且还具有每个元音的计数并将该计数存储在对象中。
function vowelCount(str){
let splitString=str.split('');
let obj={};
let vowels="aeiou";
splitString.forEach((letter)=>{
if(vowels.indexOf(letter.toLowerCase())!==-1){
if(letter in obj){
obj[letter]++;
}else{
obj[letter]=1;
}
}
});
return obj;
}
回答by HimaNair
Use this function to get the count of vowels within a string. Works pretty well.
使用此函数可获取字符串中元音的计数。工作得很好。
function getVowelsCount(str)
{
//splits the vowels string into an array => ['a','e','i','o','u','A'...]
let arr_vowel_list = 'aeiouAEIOU'.split('');
let count = 0;
/*for each of the elements of the splitted string(i.e. str), the vowels list would check
for any occurence and increments the count, if present*/
str.split('').forEach(function(e){
if(arr_vowel_list.indexOf(e) !== -1){
count++;} });
//and now log this count
console.log(count);}
//Function Call
getVowelsCount("World Of Programming");
Output for the given string would be 5. Try this out.
给定字符串的输出将是 5。试试这个。
//Code -
//代码 -
function getVowelsCount(str)
{
let arr_vowel_list = 'aeiouAEIOU'.split('');
let count = 0;
str.split('').forEach(function(e){
if(arr_vowel_list.indexOf(e) !== -1){
count++;} });
console.log(count);
}
回答by Iulius
This could also be solved using .replace()method by replacing anything that isn't a vowel with an empty string (basically it will delete those characters) and returning the new string length:
这也可以使用.replace()方法通过用空字符串替换任何不是元音的内容(基本上它会删除这些字符)并返回新的字符串长度来解决:
function vowelCount(str) {
return str.replace(/[^aeiou]/gi, "").length;
};
or if you prefer ES6
或者如果你更喜欢 ES6
const vowelCount = (str) => ( str.replace(/[^aeiou]/gi,"").length )
回答by Radu Chiriac
Use matchbut be careful as it can return a nullif no match is found
使用match但要小心,因为如果找不到匹配项,它可能会返回空值
const countVowels = (subject => (subject.match(/[aeiou]/gi) || []).length);
回答by maximast
Just use this function [for ES5] :
只需使用此功能 [对于 ES5] :
function countVowels(str){
return (str.match(/[aeiou]/gi) == null) ? 0 : str.match(/[aeiou]/gi).length;
}
Will work like a charm
会像魅力一样工作

