获取 JavaScript 中某个字符出现的次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6702757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:52:02  来源:igfitidea点击:

Get number of occurrences of a character in JavaScript

javascript

提问by Upvote

I have a string that devides some data using ','. Now I want to count the occurences of ','in that string. I tried:

我有一个字符串,它使用','. 现在我想计算该','字符串中 的出现次数。我试过:

var match = string.match('/[,]/i');

But this gives me null If I try to get the length of the match array. Any ideas?

但这给了我 null 如果我尝试获取匹配数组的长度。有任何想法吗?

回答by Chandu

If you need to check the occurances of a simple pattern as "," then better don't use regular expressions.

如果您需要将简单模式的出现情况检查为“,”,那么最好不要使用正则表达式。

Try:

尝试:

var matchesCount = string.split(",").length - 1;

回答by jfriend00

Remove the quotes and add the g flag:

删除引号并添加 g 标志:

var str = "This, is, another, word, followed, by, some, more";
var matches = str.match(/,/g);
alert(matches.length);    // 7

jsfiddle here: http://jsfiddle.net/jfriend00/hG2NE/

jsfiddle在这里:http: //jsfiddle.net/jfriend00/hG2NE/

回答by joeytwiddle

This gistclaimed that regexp was the most efficient technique.

这个要点声称正则表达式是最有效的技术。

Edit:However the performance benchmarkprovided by Jobin the comments suggest that the splittechnique is now faster. So I would recommend that nowadays.

编辑:然而,Job在评论中提供的性能基准表明该技术现在更快了。所以我会推荐现在。split

But anyway, if you do go with the regexp approach, you should be aware that if there are no matches, then String::match()returns null, and not an empty array as you might expect:

但无论如何,如果您确实使用 regexp 方法,您应该知道如果没有匹配项,则String::match()返回 null,而不是您可能期望的空数组:

> 'foo'.match(/o/g)
[ 'o', 'o' ]

> 'foo'.match(/o/g).length
2

> 'foo'.match(/x/g)
null

> 'foo'.match(/x/g).length
TypeError: Cannot read property 'length' of null

One simple way to deal with this is to substitute an empty array if the result is null:

处理此问题的一种简单方法是,如果结果为 null,则替换为空数组:

var count = (string.match(/,/g) || []).length;

Or this avoids creating the empty array, but requires two lines of code:

或者这样可以避免创建空数组,但需要两行代码:

var match = string.match(/,/g);
var count = match ? match.length : 0;

回答by agent-j

Count number of matches of a regex in Javascript

计算Javascript中正则表达式的匹配数

you need the /gglobal flag

你需要/g全球旗帜

Edit: I didn't need the 'ticks' below.

编辑:我不需要下面的“勾号”。

var count = string.match(/,/g).length; 

回答by rubergly

This gives nullbecause '/[,]/i'is not a regex. As explained at the MDN, if a non-regex is passed to string.match, then it will be converted to a regex using new Regex(obj).

这给出了null因为'/[,]/i'不是正则表达式。如MDN 中所述,如果将非正则表达式传递给string.match,则它将使用 转换为正则表达式new Regex(obj)

What you want is to pass the actual regex object, /[,]/i(or simply /,/i). "1,2,3".match(/,/i)will work as you expect in terms of matching.

你想要的是传递实际的正则表达式对象,/[,]/i(或简单地/,/i)。"1,2,3".match(/,/i)在匹配方面将按您的预期工作。

However, as Cybernate pointed out, a regex is overkill for this kind of problem. A better solution is to split the string:

然而,正如 Cyber​​nate 所指出的,正则表达式对于这类问题来说太过分了。更好的解决方案是拆分字符串:

var str = "1,2,3,4,5";
var len = str.split(",").length - 1;

回答by Rahul Ranjan

function get_occurrence(varS,string){//Find All Occurrences
    c=(string.split(varS).length - 1);
    return c;
}
string="Hi, 1,2,3";
console.log(get_occurrence(",",string));

Use get_occurrence(varS,string) to find occurrence of both characters and string in a String.

使用 get_occurrence(varS,string) 查找字符串中字符和字符串的出现。

回答by Sumant Singh

Use the following code to divide some data using ',' from a statement:

使用以下代码从语句中使用“,”分割一些数据:

 var str = "Stack,Overflow,best,for,coder"    
 var matchesCount = str.split(",").length;
 var vallueArray = str.split(',', matchesCount);
 var value1= "";
 for (var i = 0 ; i < vallueArray.length; i++) {
         value1= value1+ vallueArray [i] + " ";
    }
  document.getElementById("txt1").value = value1;