In Javascript is there a function that returns the number of times that a given string occurs?
I need to return a numeric value that is equal to the number of times that a given string occurs within a particular string for instance:
var myString = "This is a test text"
If I had to search for ‘te‘ in the above string it would return 2.
Very nearly: You can use
String#matchto do this:That uses the regular expression
/te/g(search for “te” literally, globally) and asks the string to return an array of matches. The array’s length is then the count.Naturally that creates an intermediary array, which may not be ideal if you have a large result set. If you don’t mind looping:
That uses
RegExp#testto find matches without creating intermediary arrays. (Thanks to kennebec for the comment pointing out that my earlier use ofRegExp#execin the above created intermediary arrays unnecessarily!) Whether it’s more efficient will depend entirely on how many of these you expect to match, since the version creating the one big array will probably be optimized within theString#matchcall and so be faster at the expense of more (temporary) memory use — a large result set may bog down trying to allocate memory, but a small one is unlikely to.Edit Re your comment below, if you’re not looking for patterns and you don’t mind looping, you may want to do this instead:
There’s no pre-baked non-RegExp way to do this that I know of.