I have updated this answer.
(我已经更新了这个答案。)
I like the idea of using a match better, but it is slower:(我更喜欢使用匹配的想法,但速度较慢:)
console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3
console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4
jsfiddle
(的jsfiddle)
Use a regular expression literal if you know what you are searching for beforehand, if not you can use the RegExp
constructor, and pass in the g
flag as an argument.
(如果您事先知道要搜索的内容,请使用正则表达式文字,否则可以使用RegExp
构造函数,并将g
标记作为参数传入。)
match
returns null
with no results thus the || []
(match
返回null
,没有结果,因此|| []
)
|| []
The original answer I made in 2009 is below.
(我在2009年做出的原始答案如下。)
It creates an array unnecessarily, but using a split is faster (as of September 2014).(它不必要地创建一个数组,但使用拆分更快 (截至2014年9月)。)
I'm ambivalent, if I really needed the speed there would be no question that I would use a split, but I would prefer to use match.(我很矛盾,如果我真的需要速度,毫无疑问我会使用分裂,但我宁愿使用匹配。)
Old answer (from 2009):
(旧答案(2009年起):)
If you're looking for the commas:
(如果您正在寻找逗号:)
(mainStr.split(",").length - 1) //3
If you're looking for the str
(如果你正在寻找str)
(mainStr.split("str").length - 1) //4
Both in @Lo's answer and in my own silly jsperf test split comes ahead in speed, at least in Chrome, but again creating the extra array just doesn't seem sane.
(在@Lo的答案和我自己的愚蠢的jsperf测试中, 两者都在速度方面领先,至少在Chrome中,但再次创建额外阵列似乎并不健全。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…