2

I have following RegExp and it is working fine

 var reg = new RegExp(/(.{1,4})/g);

But now i want to replace 4 with variable called limit then it is not working

 var reg = new RegExp("/(.{1,"+ limit +"})/g");

How could i use variable instead of fixed value in above RegExp?

1
  • /(.{1,4})/g is RegExp literal, so you don't even need to call constructor here. Commented Jan 29, 2013 at 11:21

3 Answers 3

6

Drop the /. RegExp expects a string or a regex. Then it takes a second parameter where you can specify the flags.

var reg = new RegExp("(.{1,"+ limit +"})", "g");

More here https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions

Sign up to request clarification or add additional context in comments.

Comments

4

Like this (you don't need the /):

 var reg = new RegExp(".{1,"+ limit +"}", "g");

Comments

3

Use it like this,

var reg = new RegExp("(.{1,"+ limit +"}", "g");

The second parameter is used for options. And the pattern does not take any delimiter.

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.