-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,512
  • 2
  • 22
  • 35

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
  • 914,110
  • 126
  • 1,211
  • 1,335
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
  • 43,180
  • 11
  • 50
  • 79