1

I am trying to make my regular expression generic by using parameters. However, the RegExp does not work when I use variables:

The below regular expression works properly where I limit my input to 7 characters.

var specialCharactersValidation = new RegExp(/^[a-zA-Z0-9]{7}$/);

But when I make it generic:

var characterCount = parseInt(attrs.limitCharacterCount); // Value is 7 and type is int
console.log(characterCount); // Value is 7
var specialCharactersValidation = new RegExp(/^[a-zA-Z0-9]{characterCount}$/);

This is the console for the above code. The regex does not compile with the character count.

7
requestShipmentDirectives.js:73 /^[a-zA-Z0-9]{characterCount}$/ false

This does not work. And neither does the below one:

var characterCount = parseInt(attrs.limitCharacterCount); // Value is 7 and type is int
console.log(characterCount); // Value is 7
var specialCharactersValidation = new RegExp("/^[a-zA-Z0-9]{"+characterCount+"}$/");

This is the console for above code:

7
9requestShipmentDirectives.js:73 /\/^[a-zA-Z0-9]{7}$\// false

RegExp compiles but never works.

The output is always false.

Is there anything missing?

1 Answer 1

3

You should use the RegExp without /.../ to allow the use of variables in a 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 the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

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.