计算Javascript中字符串中出现的字符数 [英] Count the number of occurrences of a character in a string in Javascript

查看:95
本文介绍了计算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";

我想找到逗号的计数,字符,即3.以逗号分割后的单个字符串的计数,即4。

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.

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

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

推荐答案

我已更新此答案。我喜欢更好地使用匹配的想法,但速度较慢:

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

如果您事先知道要搜索的内容,请使用正则表达式文字,否则可以使用 RegExp 构造函数,并将 g 标记作为参数传递。

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.

匹配返回 null ,没有结果,因此 || []

match returns null with no results thus the || []

我在2009年做出的原始答案如下。它会不必要地创建一个数组,但使用拆分更快(截至2014年9月)。我很矛盾,如果我真的需要速度,毫无疑问我会使用分组,但我更愿意使用匹配。

The original answer I made in 2009 is below. It creates an array unnecessarily, but using a split is faster (as of September 2014). 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.

旧答案(来自2009):

Old answer (from 2009):

如果您正在寻找逗号:

(mainStr.split(",").length - 1) //3

如果你'重新寻找str

If you're looking for the str

(mainStr.split("str").length - 1) //4

@ Lo的答案和我自己的傻瓜 jsperf test 分裂速度提升,至少在Chrome中,但再次创建额外阵列似乎并不健全。

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.

这篇关于计算Javascript中字符串中出现的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆