[英]Javascript RegEx String with Variable
I have the following RegEx that works: 我有以下正则表达式有效:
var expression = /s\[0\]\[children\]\[.*?\]\[/g;
var replace_string = "s[" + count + "][children][" + subCount + "]";
$input.attr('name', $input.attr('name').replace(expression, replace_string));
Now I am wanting to replace the 0 in the above regex with a variable, "count". 现在,我想用变量“ count”替换上述正则表达式中的0。 I have read up that it needs to be turned into a string, which I have done:
我已经读过它需要变成一个字符串,我已经完成了:
var expression = "/s\\[" + count + "\\]\\[children\\]\\[.*?\\]/g";
But that doesn't want to work for some reason, what am I doing wrong? 但这并不能出于某种原因而起作用,我在做什么错呢?
Cheers 干杯
每当您想从正则表达式中调用变量时,都需要使用RegExp
构造函数。
var expression = new RegExp("s\\[" + count + "\\]\\[children\\]\\[.*?\\]", "g");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.