regex - Dynamic Regular Expression Generation in JavaScript -


i trying make regular expression generic using parameters. however, regexp not work when use variables:

the below regular expression works limit input 7 characters.

var specialcharactersvalidation = new regexp(/^[a-za-z0-9]{7}$/); 

but when make generic:

var charactercount = parseint(attrs.limitcharactercount); // value 7 , type int console.log(charactercount); // value 7 var specialcharactersvalidation = new regexp(/^[a-za-z0-9]{charactercount}$/); 

this console above code. regex not compile character count.

7 requestshipmentdirectives.js:73 /^[a-za-z0-9]{charactercount}$/ false 

this not work. , neither below one:

var charactercount = parseint(attrs.limitcharactercount); // value 7 , type int console.log(charactercount); // value 7 var specialcharactersvalidation = new regexp("/^[a-za-z0-9]{"+charactercount+"}$/"); 

this console above code:

7 9requestshipmentdirectives.js:73 /\/^[a-za-z0-9]{7}$\// false 

regexp compiles never works.

the output false.

is there missing?

you should use regexp without /.../ allow use of variables in regular expression, e.g.:

var specialcharactersvalidation = new regexp("^[a-za-z0-9]{" + charactercount + "}$"); 

and double-escape special characters inside.

from mdn:

the literal notation provides compilation of regular expression when expression evaluated. use literal notation when regular expression remain constant. example, if use literal notation construct regular expression used in loop, regular expression won't recompiled on each iteration.


Comments