Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count how many times a string appears within another string

I have a string which points to a CSS file

../../css/style.css

I want to find out how many

../

are within the string.

How do I get this with JavaScript?

like image 965
dotty Avatar asked Dec 16 '10 14:12

dotty


2 Answers

You don't need a regex for this simple case.

var haystack = "../../css/style.css";
var needle   = "../";
var count    = haystack.split(needle).length - 1;
like image 55
kindall Avatar answered Oct 09 '22 10:10

kindall


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.

like image 41
Andy E Avatar answered Oct 09 '22 09:10

Andy E