Counting number of vowels in a string with JavaScript

前端 未结 18 1579
旧巷少年郎
旧巷少年郎 2020-12-08 23:53

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()

18条回答
  •  失恋的感觉
    2020-12-09 00:42

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

提交回复
热议问题