简体   繁体   中英

Properly escape variable inside RegEx (JavaScript)

Didn't want to ask, but I gave up :-( I can't find the solution

I can't get how to escape the variable/string.

var highlight_chars_count = {{highlight_chars_count}};
var regex_string = "/(^\\w{" + highlight_chars_count + "})/";
var regex = new RegExp(regex_string);
$('h1').html(function(i, v) {
    return v.replace(regex, "<span>$1</span>");
});

This pattern works (without " and a variable)

var regex = new RegExp(/(^\w{2})/);

I think the solution is here JavaScript regex pattern concatenate with variable … but can't transfer that to my regex.

The variable {{highlight_chars_count}} is a twig variable. Unfortunately I can't insert the variable into the regex pattern either.

You do not need / and you can do without the capturing group:

var regex_string = "^\\w{" + highlight_chars_count + "}";

and then

return v.replace(regex, "<span>$&</span>"); 
                                ^

Note that the regex delimiters ( /.../ ) are necessary when you declare a regex with a regex literal notation when a regex is static (eg var rx = /abc/g ). Here, you use a constructor notation .

Also, $& backreference refers to the whole match text, so, no need enclosing the whole pattern with a capturing group.

More information on RegExp regex literal and constructor notation at MDN

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