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

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

如果您事先知道要搜索的内容,请使用正则表达式文字,否则可以使用 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.

match 返回 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 的回答和我自己愚蠢的性能测试中,至少在速度上都领先在 Chrome 中,但再次创建额外的数组似乎并不明智.

Both in @Lo's answer and in my own silly performance 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天全站免登陆