使用JavaScript计算字符串中元音的数量

时间:2015-04-04 19:12:36

标签: javascript string

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

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;
}

20 个答案:

答案 0 :(得分:23)

你可以用一个小的正则表达式实现这个:

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

这只与正则表达式匹配(g使其搜索整个字符串,i使其不区分大小写)并返回匹配数。我们检查null,如果没有匹配(即没有元音),那么返回0。

答案 1 :(得分:6)

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

&#13;
&#13;
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
&#13;
&#13;
&#13;

答案 2 :(得分:3)

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

你不需要转换任何内容,如果需要,Javascript的错误处理足以暗示你这么简单的功能。

答案 3 :(得分:1)

Short和ES6,可以使用功能count(str);

const count = str => (str.match(/[aeiou]/gi) || []).length;

答案 4 :(得分:1)

随着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;    
}

答案 5 :(得分:1)

您可以使用spread operator将给定的字符串转换为数组,然后可以将filter()的字符仅转换为元音(不区分大小写)。

然后,您可以检查数组的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

答案 6 :(得分:1)

使用match但要小心,因为如果找不到匹配项,它可以返回 null

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

答案 7 :(得分:0)

这也可以使用.replace()方法解决,通过替换任何不带空字符串的元音(基本上它将删除这些字符)并返回新的字符串长度:

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

或者如果您更喜欢ES6

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

答案 8 :(得分:0)

这是最短的解决方案

 function getCount(str) {
 return (str.match(/[aeiou]/ig)||[]).length;
 }

答案 9 :(得分:0)

Function vowels(str){
   let count=0;
   const checker=['a','e','i','o','u'];
   for (let char of str.toLowerCase){
      if (checker.includes(char)){
        count++;
      }
   return count;
}


Function vowels(str){
   const match = str.match(/[aeiou]/gi);
   return match ? match.length : 0 ;
}

答案 10 :(得分: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)" />

答案 11 :(得分:0)

只需使用此功能[对于ES5]:

kernel-module.ko

会像魅力一样工作

答案 12 :(得分:0)

const containVowels = str => {
  const helper = ['a', 'e', 'i', 'o', 'u'];

  const hash = {};

  for (let c of str) {
    if (helper.indexOf(c) !== -1) {
      if (hash[c]) {
        hash[c]++;
      } else {
        hash[c] = 1;
      }
    }
  }

  let count = 0;
  for (let k in hash) {
    count += hash[k];
  }

  return count;
};

console.log(containVowels('aaaa'));

答案 13 :(得分:0)

    (A)   
     const countVowels = data => [...data.toLowerCase()].filter(char => 'aeiou'.includes(char)).length;

    (B)    
      const countVowels = data => data.toLowerCase().split('').filter(char => 'aeiou'.includes(char)).length;

    countVowels("Stackoverflow") // 4 

答案 14 :(得分:0)

使用此函数可获取字符串中元音的数量。效果很好。

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");

给定字符串的输出为5。试试看。

//代码-

  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);
   }

答案 15 :(得分:0)

以下内容有效且简短:

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


console.log(countVowels("abracadabra")); // 5
console.log(countVowels(""));            // 0

答案 16 :(得分:0)

您可以使用简单的include函数,如果给定数组包含给定字符,则返回true,否则返回false。

注意:include()方法区分大小写。因此,在比较字符之前,请将其转换为小写,以免丢失所有可能的大小写。

for (var i = 0; i <= string.length - 1; i++) {
  if ('aeiou'.includes(string[i].toLowerCase())) {
    vowelsCount += 1;
  }
}

答案 17 :(得分:0)

另一种方法(使用reduce

   function getVowels(str) {
     return Array.from(str).reduce((count, letter) => count + 'aeiou'.includes(letter), 0);
   }

答案 18 :(得分:0)

我的解决方案:

const str = "In West Philadephia, born and raised.";
const words = str.split("");

function getVowelCount() {
    return words.filter(word => word.match(/[aeiou]/gi)).length;
}

console.log(getVowelCount());

输出:12

答案 19 :(得分:-1)

function vowels_count()
{
    var count = 0;
    var a_count = 0;
    var e_count = 0;
    var i_count = 0;
    var o_count = 0;
    var u_count = 0;
    var str_arr = "afhfvhugiusholhriefhkebruguheuhkujhkuthbuhef";

    for ( i=0; i <= str_arr.length -1 ; i++)
    {
        if ( str_arr[i] == 'a' )
        {
            a_count++;
        }
        if ( str_arr[i] == 'e' )
        {
            e_count++;
        }
        if ( str_arr[i] == 'i' )
        {
            i_count++;
        }
        if ( str_arr[i] == 'o' )
        {
            o_count++;
        }
        if ( str_arr[i] == 'u' )
        {
            u_count++;
        }

    }
    console.log("a's count is" + " " + a_count );
      console.log("e's count is" + " " + e_count );
       console.log("i's count is" + " " + i_count );
        console.log("o's count is" + " " + o_count );
         console.log("u's count is" + " "+  u_count );

}    
相关问题