【问题标题】:Counting number of vowels in a string with JavaScript用 JavaScript 计算字符串中元音的数量
【发布时间】:2015-04-04 19:12:35
【问题描述】:

我正在使用基本的 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;
}

【问题讨论】:

  • 在 string.length 之后的 for 循环中,如果不使用

标签: javascript string


【解决方案1】:

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

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

这仅匹配正则表达式(g 使其搜索整个字符串,i 使其不区分大小写)并返回匹配数。我们检查 null 以防没有匹配项(即没有元音),在这种情况下返回 0。

【讨论】:

    【解决方案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

    【讨论】:

    • 你好,但是过滤方法会删除重复的,我的意思是如果字符串有两个a,例如过滤方法只会返回第一个?没有?
    【解决方案3】:
    function countVowels(subject) {
        return subject.match(/[aeiou]/gi).length;
    }
    

    您不需要转换任何东西,Javascript 的错误处理足以在需要时提示您这样一个简单的功能。

    【讨论】:

    • subject 不包含任何元音时不起作用。
    • return (subject.match(/[aeiou]/gi) || []).length; 改成这个以防万一
    【解决方案4】:

    Short 和 ES6,可以使用函数 count(str);

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

    【讨论】:

      【解决方案5】:

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

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

      或者如果你更喜欢 ES6

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

      【讨论】:

        【解决方案6】:

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

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

        【讨论】:

          【解决方案7】:

          您可以使用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

          【讨论】:

            【解决方案8】:

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

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

            【讨论】:

            • 嗨,你应该解释你的答案。所以其他寻找答案的人会明白。谢谢
            【解决方案9】:

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

            注意:includes() 方法区分大小写。所以在比较一个字符之前将其转换为小写以避免丢失所有可能的情况。

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

            【讨论】:

              【解决方案10】:

              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】:

                这是最短的解决方案

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

                【讨论】:

                  【解决方案12】:
                  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 ;
                  }
                  

                  【讨论】:

                    【解决方案13】:

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

                    【讨论】:

                      【解决方案14】:

                      随着 ES5 中 forEach 的引入,这可以通过一种更紧凑的方式以函数式方法实现,并且还可以对每个元音进行计数并将计数存储在一个 Object 中。

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

                      【讨论】:

                        【解决方案15】:

                        我的解决方案:

                        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

                        【讨论】:

                          【解决方案16】:

                          您可以使用简单的正则表达式轻松解决此问题。 match() 方法将字符串与正则表达式变量匹配。如果是匹配则返回一个数组,如果没有找到匹配则返回null。

                          function getVowels(str) {
                            let vowelsCount = 0;
                          
                            const regex = /[aiueo]/gi;
                            vowelsCount = str.match(regex);
                          
                            return vowelsCount ? vowelsCount.length : 0;
                          }
                          
                          console.log(getVowels('Hello World')) => return 3
                          console.log(getVoewls('bbbcccddd') => return 0

                          【讨论】:

                            【解决方案17】:

                            只需使用此功能 [for ES5] :

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

                            会像魅力一样工作

                            【讨论】:

                              【解决方案18】:
                                  (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 
                              

                              【讨论】:

                                【解决方案19】:

                                以下有效且简短:

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

                                【讨论】:

                                  【解决方案20】:

                                  另一种方法(使用reduce):

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

                                  【讨论】:

                                    【解决方案21】:

                                    这是我的解决方案:

                                    function getVowelsCount(s) {
                                          let vowels = ["a", "e", "i", "o", "u"];
                                          let count=0;
                                    
                                        for(let v of s) {
                                            if(vowels.includes(v)){
                                                console.log(v);
                                                count=count+1;
                                            }
                                               
                                        }
                                         console.log(count);
                                    
                                    }
                                    

                                    【讨论】:

                                      【解决方案22】:

                                      经过研究并且没有使用正则表达式,这是我发现对于像我这样的新开发人员来说最容易理解的内容。

                                      function vowelCount (string) {
                                        let vowel = "aeiouy"; // can also be array
                                        let result = 0;
                                      
                                        for (let i = 0; i < string.length; i++) {
                                          
                                          if (vowel.includes(string[i].toLowerCase())) {
                                            result++;
                                          }
                                        }
                                      
                                          
                                        return result;
                                      }
                                      
                                      
                                      
                                      console.log(vowelCount("cAkeYE"));

                                      【讨论】:

                                      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
                                      猜你喜欢
                                      • 2011-09-05
                                      • 1970-01-01
                                      • 2019-09-01
                                      • 2021-06-09
                                      • 2020-02-19
                                      • 2018-04-30
                                      • 2020-08-07
                                      • 1970-01-01
                                      • 1970-01-01
                                      相关资源
                                      最近更新 更多