计算字符串在另一个字符串中出现的次数 [英] count how many times a string appears within another string
本文介绍了计算字符串在另一个字符串中出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个指向CSS文件的字符串
I have a string which points to a CSS file
../../css/style.css
我想了解多少
../
在字符串中。
如何使用JavaScript获得此功能?
How do I get this with JavaScript?
推荐答案
您可以使用 匹配
,然后获取结果数组的长度:
You can use match
with a regular expression, and get the length of the resulting array:
var str = "../../css/style.css";
alert(str.match(/\.\.\//g).length);
//-> 2
请注意。
和 /
是正则表达式中的特殊字符,因此需要根据我的示例进行转义。
Note that .
and /
are special characters within regular expressions, so they need to be escaped as per my example.
这篇关于计算字符串在另一个字符串中出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文