Jump to content
Larry Ullman's Book Forums

Javascript Regular Expression Performance

Recommended Posts



I have a form field that needs to be validated before any attempt is made to upload the contents to a database.  Fear not, the test is performed again in PHP before the db update!


I am using jQuery and the associated jQuery form validation module.  Everything works fine but I have found that three slightly different regular expression tests can be used - my question is: are there any performance or other reasons why one particular approach is best?


Here's the code together with an explanation of the regex:



    function (value, element) {

     var valx = String(value);

     // var regex_tester = new RegExp(

     var regex_tester = /^(http:\/\/)(\S)+(\?u=){1}(\S)+(\&id=){1}(\S)+(\&e=){1}(\S)+/;


     var regex_tester = /

        // must start with what follows

      "^" +

      // now the http bit...

      "(http:\/\/)" +

      // any letters, numbers or periods (one or more of them)

      "(\\S)+" +

      // must contain ?u= (once)

      "(\?u=){1}" +

      // now more letters, numbers etc..

      "(\\S)+" +

      // now &id= (once)

      "(\&id=){1}" +

      // now more letters, numbers etc..

      "(\\S)+" +

      // now &e= (once)

      "(\&e=){1}" +

      // now more letters, numbers etc..

      "(\\S)+" +



     // Note:  all 3 of the following tests work OK...

     // if (regex_tester.test(valx))

     // if (/^(http:\/\/)(\S)+(\?u=){1}(\S)+(\&id=){1}(\S)+(\&e=){1}(\S)+/.test(valx))

     if (valx.match(/^(http:\/\/)(\S)+(\?u=){1}(\S)+(\&id=){1}(\S)+(\&e=){1}(\S)+/))

      return true;


      return false;



    "Error - The Internet address (URL) does not have some of the required/expected details."

    );  // end details check 

I could not get the "...new RegExp approach to work thus it is commented out.


Any thoughts/advice will be most appreciated.


Thanking you in anticipation,


Cheers from Oz.

Link to post
Share on other sites

Use the test method when you just want to check for a match, and use match when you actually want to get the match(es) back.

The literal syntax (i.e., //) will always be faster than the new RegExp syntax, and as such, I only use new RegExp when I need to embed a variable in my regex.

  • Upvote 1
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...