More about regular expressions in Javascript

Aah !! Regular expressions

I have got confused most of the times, I need to escape special characters when specifying a regular expression.

Let us take an example of simple date format

There are two ways, you can specify your regular expression

// Please note that your regular expression literal object must be surrounded
// between forward slashes as is done below.

// Since forward slash (/) has a special meaning in regular expressions
// it need to be escaped by a backslash ()
var regex = /^d{2}/d{2}/d{4}$/

/* / -- Used to signify that a regex literal follows.
* ^ - Starts with
* d{2} - 2 digits (date)
* / - Escaping the forward slash
* d{2} - 2 digits (Month)
* / - Escaping the forward slash
* d{4} - 4 digits (Year)
* $ - end of string.
* / - specifies the end of regex literal.

// Things become more complex when you want to specify
// regular expression in a String

// Please note the difference between the regex literal and the string regex
// Here we have to escape the backslash as well.
// So the number of backslashes are doubled.

var regex = new RegExp("^\d{2}\/\d{2}\/\d{4}");

* ^ - Starts with
* \d{2} - 2 digits (date)
* \/ - Escaping the forward slash
* \d{2} - 2 digits (Month)
* \/ - Escaping the forward slash
* \d{4} - 4 digits (Year)
* $ - end of regex.

Please note that you have to escape all those characters which have a special meaning in Regular expressions.
Just place a backslash before that character. (2 backslashes if you are specifying regex as a string literal)
List of characters that need to be escaped are :

[, ], ., ?, *, +, /, , {, }, |, (, )

Related Post :

0 Replies to “More about regular expressions in Javascript”

  1. As i understand 'd' here stands for digit then this regex wont give correct dates like it will parse the value 99/99/9999 while its not a valid date.. isn't it?

  2. Dear aashu,

    Yes, you are absolutely right. But this example is not a very precise regular expression for date validation.

    If you want to write a exact date validator, just have a look at the link given in the post, 10 java regular expressions that you must know. 🙂

  3. Please note that it is always better to use ^ in the beginning and $ in the end.

    var REAL_NUMBER = new RegExp(“\d+(\.\d+)?”);

    The above code will give you alert true.

    Correct code:
    var REAL_NUMBER = new RegExp(“^\d+(\.\d+)?$”);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.