-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
  • 2,186
  • 2
  • 19
  • 33

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
  • 857,932
  • 118
  • 1,152
  • 1,264
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
  • 40,575
  • 10
  • 44
  • 74