如何计算字符串中的字符串出现? [英] How to count string occurrence in string?
本文介绍了如何计算字符串中的字符串出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我在Javascript中尝试做的事情:
How can I count the number of times a particular string occurs in another string. For example, this is what I am trying to do in Javascript:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
推荐答案
<$ c正则表达式中的$ c> g ( global 的缩写)表示搜索整个字符串而不是仅查找第一个匹配项。这匹配是
两次:
The g
in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is
twice:
var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);
并且,如果没有匹配项,则返回 0
:
And, if there are no matches, it returns 0
:
var temp = "Hello World!";
var count = (temp.match(/is/g) || []).length;
console.log(count);
这篇关于如何计算字符串中的字符串出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文