0

Same question has been asked here: How to pass a regular expression as a function parameter, and I tried it like this:

 <!DOCTYPE html>
  <html>
    <head>
     <meta charset="UTF-8">
     <title>Insert title here</title>
        <script type="text/javascript">
             function validate(value, regexp){
                   //escape special characters
                   var regexp = regexp.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').replace(/\x08/g, '\\x08');
                  return new RegExp(regexp,'g').test(value);
             }
       </script>
   </head>
   <body>
      <script>
           var regexp = "^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$";
           alert(validate("[email protected]",regexp))
      </script>
  </body>
</html>

but it doesn't work,and I am sure the string of pattern is right,and I have tested it in firebug like this:

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test("[email protected]")

It matches email correctly.so Please tell what mistakes I have made,thanks.

1
  • Why are you escaping all the special characters? Commented Nov 20, 2014 at 9:27

1 Answer 1

0

You need to escape the \ one more time while giving it inside the delimiter "

var regexp = "^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";

OR

var regexp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
Sign up to request clarification or add additional context in comments.

1 Comment

Can I take the "var regexp = regexp.replace(/([-()[]{}+?*.$\^|,:#<!\])/g, '\\$1').replace(/\x08/g, '\\x08');" as escaping?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.