I have to count occurences of symbols from the list (var. "pattern") in each string (element) of array. I want to make it more universal, by setting pattern in variable. But, when I try to do it by using RegExp object, it doesn't work.
I can't understand the difference in two parts of code:
This variant doesn't work.
var pattern = "@#%";
var arr = ['T@wn','D#nse Cr%wd','Cr#m#n#l M@st@m@nd'];
for(var i=0; i < arr.length; i++){
l = '/[^'+pattern+']/';
g = new RegExp(l,"gi");
console.log(arr[i].replace(g,"").length);
}
The result will be:
4
11
18
The same variant, but without RegExp object, works fine:
var arr = ['T@wn','D#nse Cr%wd','Cr#m#n#l M@st@m@nd'];
for(var i=0; i < arr.length; i++){
console.log(arr[i].replace(/[^@#%]/gi,"").length);
}
The result will be:
1
2
6
Can you explain the difference?
Thanks in advance.