suntrop
suntrop

Reputation: 785

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.

Upvotes: 4

Views: 594

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

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 (e.g. 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

Upvotes: 4

Related Questions