简体   繁体   中英

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:

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]; ?>"; to replace the test.com part in the if statement. 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):

var regex = new RegExp("@" + someVar + "\\s*$");
//                                      ^--- Notice the escaped backslash

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM