-1

By this method I want to use a variable in regex but it creates an extra / in the output:

var counter = 0,
    replace = "/\$" + counter;
    regex = new RegExp(replace);
    console.log(regex);

The output is /\/$0/ while I expected /\$0/, would you tell me what's wrong with it?

Muhammad Musavi
  • 1,679
  • 1
  • 15
  • 31

2 Answers2

0

The / at the front is being escaped because / characters must be escaped in regular expressions delimited by / (which is how the console expresses your regex when you log it).

The \ before the $ is lost because \ is an escape character in JavaScript strings as well as in regular expressions. Log replace to see that the \$ is parsed as $. You need to escape the \ itself if you want it to survive into the regular expression.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
0

You're adding a / to your regular expression string before it's generated (generation adds /), and you need to escape the backslash:

var counter = 0;
var replace = "\\$" + counter;
var regex = new RegExp(replace);
console.log(regex);
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67