4

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.

Community
  • 1
  • 1
suntrop
  • 775
  • 3
  • 10
  • 24

1 Answers1

4

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563