var reExample = /pattern/;
var reExample = new RegExp("pattern");
Assuming you know the regular expression pattern you are going to use, there is no real difference between the two; however, if you don't know the pattern ahead of time (e.g, you're retrieving it from a form), it can be easier to use the
exec() method takes one argument, a string, and checks whether that string contains one or more matches of the pattern specified by the regular expression. If one or more matches is found, the method returns a result array with the starting points of the matches. If no match is found, the method returns
test() method also takes one argument, a string, and checks whether that string contains a match of the pattern specified by the regular expression. It returns
true if it does contain a match and
false if it does not. This method is very useful in form validation scripts. The code sample below shows how it can be used for checking a social security number. Don't worry about the syntax of the regular expression itself. We'll cover that shortly.
Let's examine the code more closely:
checkSsn()is created. This function takes one argument:
ssn, which is a string. The function then tests to see if the string matches the regular expression pattern by passing it to the regular expression object's
test()method. If it does match, the function alerts "VALID SSN". Otherwise, it alerts "INVALID SSN".
Flags appearing after the end slash modify how a regular expression works.
iflag makes a regular expression case insensitive. For example,
/aeiou/imatches all lowercase and uppercase vowels.
gflag specifies a global match, meaning that all matches of the specified pattern should be returned.
There are several String methods that take regular expressions as arguments.
search() method takes one argument: a regular expression. It returns the index of the first character of the substring matching the regular expression. If no match is found, the method returns -1.
"Webucator".search(/cat/); //returns 4
split() method takes one argument: a regular expression. It uses the regular expression as a delimiter to split the string into an array of strings.
"Webucator".split(/[aeiou]/); /* returns an array with the following values: "W", "b", "c", "t", "r" */
replace() method takes two arguments: a regular expression and a string. It replaces the first regular expression match with the string. If the
g flag is used in the regular expression, it replaces all matches with the string.
"Webucator".replace(/cat/, "dog"); //returns Webudogor "Webucator".replace(/[aeiou]/g, "x"); //returns Wxbxcxtxr
match() method takes one argument: a regular expression. It returns each substring that matches the regular expression pattern.
"Webucator".match(/[aeiou]/g); /* returns an array with the following values: "e", "u", "a", "o" */