小智 17
只需在正则表达式中添加空格字符即可找到空格.
可以找到空白区域\s.
如果要在单词之间找到空格,请使用\b单词边界标记.
这将匹配两个单词之间的单个空格:
"\b \b"
Run Code Online (Sandbox Code Playgroud)
(你的匹配失败的原因是\\p{L}包含匹配中的字符.因为e只有一个字符,它会被前一个匹配吃掉,并且不能匹配后面的空格e. \b避免这个问题因为它是零宽度比赛.)
// Setup
var testString = "How many spaces are there in this sentence?";
// Only change code below this line.
var expression = /\s+/g; // Change this line
// Only change code above this line
// This code counts the matches of expression in testString
var spaceCount = testString.match(expression).length;
Run Code Online (Sandbox Code Playgroud)