简体   繁体   English

计算字符串在另一个字符串中出现的次数

[英]count how many times a string appears within another string

I have a string which points to a CSS file 我有一个指向CSS文件的字符串

../../css/style.css

I want to find out how many 我想知道有多少

../

are within the string. 在字符串内。

How do I get this with JavaScript? 我如何使用JavaScript获得此功能?

You don't need a regex for this simple case. 对于这个简单的案例,您不需要正则表达式。

var haystack = "../../css/style.css";
var needle   = "../";
var count    = haystack.split(needle).length - 1;

You can use match with a regular expression, and get the length of the resulting array: 您可以使用match正则表达式,并获得结果数组的长度:

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. /是正则表达式中的特殊字符,因此需要根据我的示例进行转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM