0

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.

1 Answer 1

1

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);
}

This line should be changed from:

l = '/[^' + pattern + ']/';

to:

l = '[^' + pattern + ']';

removing the surrounding / because you are passing in the regular expression pattern as a string to the RegExp constructor.

Mozilla says about these two types:

You construct a regular expression in one of two ways:

Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:

var re = /ab+c/;

Regular expression literals provide compilation of the regular expression when the script is loaded. When the regular expression will remain constant, use this for better performance.

Or calling the constructor function of the RegExp object, as follows:

var re = new RegExp("ab+c");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.