0

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.

Annie
  • 39
  • 1
  • 7
  • possible duplicate of [How do you pass a variable to a Regular Expression JavaScript?](http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript) – James Allardice Apr 08 '14 at 09:35

1 Answers1

4

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
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • I just try but always comes true no matter what I input: var regex = new RegExp("@" + javaScriptVar + "\\s*$"); if(!regex.test(document.forms["myForm"]["email"].value){ alert("Please Enter Correct Email Domain"); return false; } – Annie Apr 08 '14 at 09:40
  • For this testing, I have used var javaScriptVar = "test.com"; – Annie Apr 08 '14 at 09:41