Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec and test methods of RegExp, and with the match, replace, search, and split methods of String.
You construct a regular expression in one of two ways:
1)Using a regular expression literal, as follows:
var re = /ab+c/;
2)Calling the constructor function of the RegExp object, as follows:
var re = new RegExp("ab+c");
Examples:
function escapeRegExp(string){
return string.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
}
Methods that use regular expressions
exec
A RegExp method that executes a search for a match in a string. It returns an array of information.
test
A RegExp method that tests for a match in a string. It returns true or false.
match
A String method that executes a search for a match in a string. It returns an array of information or null on a mismatch.
search
A String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails.
replace
A String method that executes a search for a match in a string, and replaces the matched substring with a replacement substring.
split
A String method that uses a regular expression or a fixed string to break a string into an array of substrings.