简体   繁体   中英

Unwanted slash on creating regex

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?

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM