0

I have this regexp :

var regexp = /(2\d)(\W)/gi

Now I want to set it dynamically, meaning the value 2 can be changed like this :

var regexp = /(changablevalue\d)(\W)/gi

I tried :

var regexp = "/(" + changablevalue + "\d)(\W)/gi" 

and

var changablevalue = 2
var regexp = /(changablevalue\d)(\W)/gi

but can't get it to work. What am I doing wrong here?

1 Answer 1

1

Pass your regex to RegExp constructor.

var regex = new RegExp("("+changablevalue + "\\d)(\\W)", "gi")

Example:

> var changablevalue = 2
> var regex = new RegExp("("+changablevalue + "\\d)(\\W)", "gi")
undefined
> console.log(regex)
/(2\d)(\W)/gi
undefined
> regex.test('28.')
true
> regex.test('48.')
false
Sign up to request clarification or add additional context in comments.

3 Comments

It still not working, do I need to install some additional classes?
Ah I see, the slashes
Since in the constructor you're passing the regex as a string, I believe that backslashes should be escaped. And so should the changeablevalue (if it will contain any "regex expressions", like \w for example.)

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.