Question: How do I create a regular expression?
Answer: To create a regular expression, you can use a regular expression literal or the
/elements/flags or, without the optional flags, simply: /elements/
The regular expression's
specify what you would like to match or replace.
) mode. You will find a more detailed discussion of the supported elements and flags on the
Examples of regular expression literals:
re = /^\s+|\s+$/g // any number of leading/trailing whitespaces re = /\d\d\d/ // one sequence of 3 digits (1st match only) re = /\d\d\d/g // any sequence of 3 digits re = /[0-9][0-9][0-9]/g // any sequence of 3 digits re = /jan|feb|mar|apr/i // Jan or Feb or Mar or Apr (case-insensitive) re = /"[a-z]+"/gi // any sequence of Latin letters, in quotes
The RegExp constructor has this syntax:
Examples of the
constructor (the constructor calls below create regular expressions similar to the above):
//to get \s in regular expression, pass \\s to RegExp constructor! re = new RegExp("^\\s*|\\s*$","g") re = new RegExp("\\d\\d\\d",'') re = new RegExp("\\d\\d\\d",'g') re = new RegExp("[0-9][0-9][0-9]","g") re = new RegExp("jan|feb|mar|apr","i") re = new RegExp('"[a-z]+"',"gi")
Note that in order to pass quotes to the
constructor as part of the
string, the quotes should be preceded with a backslash