Javascript 正则表达式匹配出现空值

shr*_*unk 2 html javascript regex null match

我正在尝试编写一个 javascript 函数来接收一个字符串,并计算元音的数量。显示每个元音的计数以及总计。如果每个元音都在字符串中,它工作正常,但例如,如果没有 A 或 E,它将返回 null。

有没有办法可以拦截这个并将null替换为0?或者有没有更有效的方法来实现这一目标?感谢任何可以提供帮助的人!

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
  );
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Cer*_*rus 5

您可以使用|| []作为的情况下,默认的“返回值”.match的回报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
  );
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

另外,请注意我[]从所有单字符匹配中删除了。在正则表达式中,[a]a是等价的。

||如果左侧是"truthy",则将返回运算符的左侧。
如果左侧是"falsy"||则将始终返回语句的右侧,这是我们的默认值。

如果.match找到任何结果,它将返回一个数组,这是“真实的”。
如果.match没有找到任何结果,则返回null,这是“假的”。