[英]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. 我认为解决方案是在这里JavaScript正则表达式模式连接变量 ...但不能将其转移到我的正则表达式。
The variable {{highlight_chars_count}} is a twig variable. 变量{{highlight_chars_count}}是一个树枝变量。 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
). 请注意,当正则表达式是静态的(例如
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. 此外,
$&
backreference指的是整个匹配文本,因此,不需要用捕获组封装整个模式。
More information on RegExp
regex literal and constructor notation at MDN 有关在MDN上使用
RegExp
正则表达式文字和构造函数表示法的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.