I have a string that devides some data using ','
. Now I want to count the occurences of ','
in that string. I tried:
var match = string.match('/[,]/i');
But this gives me null If I try to get the length of the match array. Any ideas?
I have a string that devides some data using ','
. Now I want to count the occurences of ','
in that string. I tried:
var match = string.match('/[,]/i');
But this gives me null If I try to get the length of the match array. Any ideas?
If you need to check the occurances of a simple pattern as "," then better don't use regular expressions.
Try:
var matchesCount = string.split(",").length - 1;
Remove the quotes and add the g flag:
var str = "This, is, another, word, followed, by, some, more";
var matches = str.match(/,/g);
alert(matches.length); // 7
jsfiddle here: http://jsfiddle.net/jfriend00/hG2NE/
This gist claimed that regexp was the most efficient technique.
Edit: However the performance benchmark provided by Job in the comments suggest that the split
technique is now faster. So I would recommend that nowadays.
But anyway, if you do go with the regexp approach, you should be aware that if there are no matches, then String::match()
returns null, and not an empty array as you might expect:
> 'foo'.match(/o/g)
[ 'o', 'o' ]
> 'foo'.match(/o/g).length
2
> 'foo'.match(/x/g)
null
> 'foo'.match(/x/g).length
TypeError: Cannot read property 'length' of null
One simple way to deal with this is to substitute an empty array if the result is null:
var count = (string.match(/,/g) || []).length;
Or this avoids creating the empty array, but requires two lines of code:
var match = string.match(/,/g);
var count = match ? match.length : 0;
Count number of matches of a regex in Javascript
you need the /g
global flag
Edit: I didn't need the 'ticks' below.
var count = string.match(/,/g).length;
function get_occurrence(varS,string){//Find All Occurrences
c=(string.split(varS).length - 1);
return c;
}
string="Hi, 1,2,3";
console.log(get_occurrence(",",string));
Use get_occurrence(varS,string) to find occurrence of both characters and string in a String.
Use the following code to divide some data using ',' from a statement:
var str = "Stack,Overflow,best,for,coder"
var matchesCount = str.split(",").length;
var vallueArray = str.split(',', matchesCount);
var value1= "";
for (var i = 0 ; i < vallueArray.length; i++) {
value1= value1+ vallueArray [i] + " ";
}
document.getElementById("txt1").value = value1;
This gives null
because '/[,]/i'
is not a regex. As explained at the MDN, if a non-regex is passed to string.match
, then it will be converted to a regex using new Regex(obj)
.
What you want is to pass the actual regex object, /[,]/i
(or simply /,/i
). "1,2,3".match(/,/i)
will work as you expect in terms of matching.
However, as Cybernate pointed out, a regex is overkill for this kind of problem. A better solution is to split the string:
var str = "1,2,3,4,5";
var len = str.split(",").length - 1;