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.

1
  • 1
    remove / in var regex_string = "/(^\\w{" + highlight_chars_count + "})/"; Commented May 10, 2016 at 14:10

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Great tips! Thanks Wiktor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.