Rajeev
Rajeev

Reputation: 1371

javascript regex obtained from a variable giving error on test: "is not a function"

in plain javascript: I am getting error when i run the below:

var arg_regex = 'myregex:/^[:a-z0-9\s!\\\/]+$/i';

regex_patt = arg_regex.replace(/^myregex:/,'');

if(regex_patt.test(stringtocheck)){
//good
} else {
//bad
}

error:

regex_patt.test is not a function

pl help. not able to figure why it would fail.

Upvotes: 0

Views: 120

Answers (2)

Sswater Shi
Sswater Shi

Reputation: 189

Try to add this line to let regex_patt to be an object:

    regex_patt = eval(regex_patt);

Upvotes: 0

freethejazz
freethejazz

Reputation: 2285

What Felix said:

regex_string = arg_regex.split('myregex:/').join('').split('/i').join('');
regex_patt = new RegExp(regex_string);

The RegExp object must be constructed from the string first.

In the above example, you're replacing a static string, so you can use string.replace('staticTextToRemove','') or use the split and join shown above.

I've heard split().join() is slightly more performant... and its a neat trick.

Upvotes: 1

Related Questions