2

I read on RegExp in javascript

And I see two ways to create new RegExp:/ab+c/i; new RegExp('ab+c', 'i'); new RegExp(/ab+c/, 'i');

But I want to create new RegExp like this:

var re = new RegExp(`\d+${variable}`, 'g');

I try but it's not working. How can I do that?

1
  • 1
    Please, leave the sample from your variable. Commented Jul 29, 2018 at 10:02

2 Answers 2

4

Escape your RegExp character class in the template literal with a \\, e.g. to escape:

  • \d, write \\d
  • \w, write \\w
  • \s, write \\s

...and so on.

let variable = 1;
const re = new RegExp(`\\d+${variable}`, 'g');

console.log(re);

More on RegeExp

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

Comments

1

You can write the whole expression as a string (to which you can concatenate the value of the variable), then use eval() to change it to a working javascript expression:

var x = "A";
var re = eval("new RegExp('\d+$" + x + "', 'g')");

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.