2015-04-04 54 views
4

我使用基本的JavaScript來計算字符串中元音的數量。下面的代碼工作,但我想清理一下。考慮到它是一個字符串,會不會使用.includes()?如果可能的話清理條件語句,我想使用類似string.includes("a", "e", "i", "o", "u")的東西。另外,是否需要將輸入轉換爲字符串?使用JavaScript計算字符串中元音的數量

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

回答

13

實際上,你可以用一個小的正則表達式做到這一點:

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

這只是對正則表達式匹配(g使得搜索整個字符串,i使得它不區分大小寫),並返回數字的比賽。我們檢查null有沒有匹配(即沒有元音),並在這種情況下返回0。

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

你不需要轉換任何東西,如果需要的話,Javascript的錯誤處理足以提示你這麼簡單的功能。

+1

當'subject'不包含任何元音時它不起作用。 – 2016-11-22 13:02:43

+0

'return(subject.match(/ [aeiou]/gi)|| [])。length;'爲了以防萬一 – maximast 2017-06-01 19:35:14

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

1

使用match但如果沒有找到匹配

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

只要使用此功能[對於ES5]要小心,因爲它可以返回一個

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

會像一個魅力

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

0

這也使用.replace()方法通過更換任何不以空字符串元音(基本上就會刪除這些字符)並返回來解決新的字符串長度:

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

或者如果你喜歡ES6

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