[英]How to have a variable inside javascript regex?
I have been searching an answer for like three days but still cannot find one that works. 我已经搜寻了大约三天的答案,但仍然找不到有效的答案。 I have this if statement in javascript block:
我在javascript块中有以下if语句:
if (!(/@test.com\s*$/.test(document.forms["myForm"]["email"].value))) {
alert("Please Enter Correct Email Domain");
return false;
}
I need to have this: var javaScriptVar = "<?php echo $ar[1]; ?>";
我需要这样:
var javaScriptVar = "<?php echo $ar[1]; ?>";
to replace the test.com part in the if statement. 替换if语句中的test.com部分。 Any idea how to do this?
任何想法如何做到这一点? Thanks.
谢谢。
Use the RegExp
constructor instead of a literal (note that you need to escape backslashes when taking this approach): 使用
RegExp
构造函数而不是文字(请注意,采用这种方法时需要转义反斜杠):
var regex = new RegExp("@" + someVar + "\\s*$");
// ^--- Notice the escaped backslash
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.