Correctly avoiding a variable inside RegEx (JavaScript)

I didn’t want to ask, but I gave up :-( I can not find a solution

I cannot get how to avoid the / string variable.

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 template works (without "and variable)

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

I think the solution here is to Concretize the JavaScript regular expression pattern with a variable ... but I can't pass this to my regular expression.

The variable {{highlight_chars_count}} is a branch variable. Unfortunately, I cannot insert a variable into the regex pattern.

+4
source share
1 answer

You do not need /, and you can do without a capture group:

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

and then

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

, (/.../) , , (, var rx = /abc/g). .

, $& backreference , .

RegExp MDN

+4

All Articles