我正在嘗試編寫一個接收字符串的javascript函數,並計算元音的數量。顯示每個元音的數量,以及總數。如果每個元音都在字符串中,它會正常工作,但如果例如沒有A或E,它將返回null。Javascript正則表達式比賽即將推出null
有沒有辦法我可以截取這個並用null替換null?還是有更高效的方法來實現這一目標?感謝任何能夠幫助的人!
function countVowels(inString) {
return outString = (
"Total vowels: " + inString.match(/[aeiou]/gi).length +
"\nTotal A's: " + inString.match(/[a]/gi).length +
"\nTotal E's: " + inString.match(/[e]/gi).length +
"\nTotal I's: " + inString.match(/[i]/gi).length +
"\nTotal O's: " + inString.match(/[o]/gi).length +
"\nTotal U's: " + inString.match(/[u]/gi).length
);
}
<form>
Enter a string to count its vowels. <br>
<input type="text" id="inString"><br>
<button type="button" onclick="console.log(countVowels(inString.value))">Count vowels</button>
</form>
呀,'match'是一種惱人的方式。我會嘗試一種不同的方法:編寫一個'函數計數(字符串,字母)'來計算'string'中'letter'的實例數,並用'count(inString,'a')',' count(inString,'e')'等等。你可以保存每一個並將它們加在一起得到元音的總數。 – Ryan
而不是'/ [a]/gi',你可以使用'/ a/gi'。這不會解決你的問題,但它有點清潔...... – Cerbrus