Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

javascript - 计算Javascript中字符串中出现的字符数(Count the number of occurrences of a character in a string in Javascript)

I need to count the number of occurrences of a character in a string.

(我需要计算一个字符串中出现的字符数。)

For example, suppose my string contains:

(例如,假设我的字符串包含:)

var mainStr = "str1,str2,str3,str4";

I want to find the count of comma , character, which is 3. And the count of individual strings after the split along comma, which is 4.

(我想找到逗号,字符的计数,这是3.和逗号分割后的单个字符串的计数,即4。)

I also need to validate that each of the strings ie str1 or str2 or str3 or str4 should not exceed, say, 15 characters.

(我还需要验证每个字符串,即str1或str2或str3或str4不应超过15个字符。)

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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中,但再次创建额外阵列似乎并不健全。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...