[removed] Counting number of vowels in a string

前端 未结 2 1670
再見小時候
再見小時候 2021-01-18 12:49

I am trying to count the number of vowels in a string, but my counter does not seem to be returning more than one. Can someone please tell me what is wrong with my code? Tha

相关标签:
2条回答
  • 2021-01-18 13:32

    return count outside of for loop, or use RegExp /[^aeiou]/ig as first parameter to .replace() with "" as replacement string, get .legnth of string returned by .replace()

    vowelLength = "aide".replace(/[^aeiou]/ig, "").length;
    
    console.log(vowelLength);
    
    vowelLength = "gggg".replace(/[^aeiou]/ig, "").length;
    
    console.log(vowelLength);

    RegExp description

    Character set

    [^xyz] A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets.

    Flags

    i ignore case

    g global match; find all matches rather than stopping after the first match


    Using spread element, Array.prototype.reduce(), String.prototype.indexOf() or String.prototype.contains() where supported

    const v = "aeiouAEIOU";
    
    var vowelLength = [..."aide"].reduce((n, c) => v.indexOf(c) > -1 ? ++n : n, 0);
    
    console.log(vowelLength);
    
    var vowelLength = [..."gggg"].reduce((n, c) => v.indexOf(c) > -1 ? ++n : n, 0);
    
    console.log(vowelLength);


    Alternatively, instead of creating a new string or new array to get .length property or iterate characters of string, you can use for..of loop, RegExp.prototype.test with RegExp /[aeiou]/i to increment a variable initially set to 0 if .test() evaluates to true for the character passed.

    var [re, vowelLength] = [/[aeiou]/i, 0]; 
    
    for (let c of "aide") re.test(c) && ++vowelLength;
    
    console.log(vowelLength); 
    
    vowelLength = 0;
    
    for (let c of "gggg") re.test(c) && ++vowelLength;
    
    console.log(vowelLength); 

    0 讨论(0)
  • 2021-01-18 13:35

    You need to also do this. use toLowerCase() also

     var vowelCount = function(str){
      var count = 0;
      for(var i = 0; i < str.length; i++){
        if(str[i].toLowerCase() == 'a' || str[i].toLowerCase() == 'i' || str[i].toLowerCase() == 'o' ||str[i].toLowerCase() == 'e' ||str[i].toLowerCase() == 'u'){
          count+=1;
        }
      }
     return count;
    }
    vowelCount('aide')
    
    0 讨论(0)
提交回复
热议问题