patternjavascriptCritical
Count the number of occurrences of a character in a string in Javascript
Viewed 0 times
theoccurrencescharacternumberstringjavascriptcount
Problem
I need to count the number of occurrences of a character in a string.
For example, suppose my string contains:
I want to find the count of comma
I also need to validate that each of the strings i.e str1 or str2 or str3 or str4 should not exceed, say, 15 characters.
For example, suppose my string contains:
var mainStr = "str1,str2,str3,str4";I want to find the count of comma
, character, which is 3. And the count of individual strings after the split along comma, which is 4.I also need to validate that each of the strings i.e str1 or str2 or str3 or str4 should not exceed, say, 15 characters.
Solution
I have updated this answer. I like the idea of using a match better, but it is slower:
Use a regular expression literal if you know what you are searching for beforehand, if not you can use the
The original answer I made in 2009 is below. It creates an array unnecessarily, but using a split is faster (as of September 2014). I'm ambivalent, if I really needed the speed there would be no question that I would use a split, but I would prefer to use match.
Old answer (from 2009):
If you're looking for the commas:
If you're looking for the str
Both in @Lo's answer and in my own silly performance test split comes ahead in speed, at least in Chrome, but again creating the extra array just doesn't seem sane.
console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3
console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4
Use a regular expression literal if you know what you are searching for beforehand, if not you can use the
RegExp constructor, and pass in the g flag as an argument.match returns null with no results thus the || []The original answer I made in 2009 is below. It creates an array unnecessarily, but using a split is faster (as of September 2014). I'm ambivalent, if I really needed the speed there would be no question that I would use a split, but I would prefer to use match.
Old answer (from 2009):
If you're looking for the commas:
(mainStr.split(",").length - 1) //3If you're looking for the str
(mainStr.split("str").length - 1) //4Both in @Lo's answer and in my own silly performance test split comes ahead in speed, at least in Chrome, but again creating the extra array just doesn't seem sane.
Code Snippets
(mainStr.split(",").length - 1) //3(mainStr.split("str").length - 1) //4Context
Stack Overflow Q#881085, score: 1118
Revisions (0)
No revisions yet.