tl; dr:通用模式计数器
// THIS IS WHAT YOU NEEDconst count = (str) => { const re = /YOUR_PATTERN_HERE/g return ((str || '').match(re) || []).length}
对于那些来到这里的人来说,他们正在寻找一种通用的方法来计算字符串中正则表达式模式的出现次数,并且如果出现的次数为零,也不希望它失败,那么您需要的是这段代码。这是一个示范:
const count = (str) => { const re = /[a-z]{3}/g return ((str || '').match(re) || []).length}const str1 = 'abc, def, ghi'const str2 = 'ABC, DEF, GHI'console.log(`'${str1}' has ${count(str1)} occurrences of pattern '/[a-z]{3}/g'`)console.log(`'${str2}' has ${count(str2)} occurrences of pattern '/[a-z]{3}/g'`)
原始答案
初始代码的问题是缺少全局标识符:
>>> 'hi there how are you'.match(/s/g).length;4
没有
g正则表达式的部分,它将仅匹配第一个匹配项并在此停止。
还要注意,您的正则表达式将对连续的空格计数两次:
>>> 'hi there'.match(/s/g).length;2
如果不希望这样做,则可以执行以下 *** 作:
>>> 'hi there'.match(/s+/g).length;1
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)