From http://www.w3schools.com (Copyright Refsnes Data)
The RegExp object is used to specify what to search for in a text
RegExp, is short for regular expression.
When you search in a text, you can use a pattern to describe what you are
searching for. RegExp IS this pattern.
A simple pattern can be a single character.
A more complicated pattern consists of more characters, and can be used for parsing, format checking, substitution and more.
You can specify where in the string to search, what type of characters to search for, and more.
The RegExp object is used to store the search pattern.
We define a RegExp object with the new keyword. The following code line defines a RegExp object called patt1 with the pattern "e":
var patt1=new RegExp("e"); |
When you use this RegExp object to search in a string, you will find
the letter "e".
The RegExp Object has 3 methods: test(), exec(), and compile().
The test() method searches a string for a specified value. Returns true or false
var patt1=new RegExp("e"); document.write(patt1.test("The best things in life are free")); |
Since there is an "e" in the string, the output of the code above will be:
true |
The exec() method searches a string for a specified value. Returns the text of the found value. If no match is found, it returns null
var patt1=new RegExp("e"); document.write(patt1.exec("The best things in life are free")); |
Since there is an "e" in the string, the output of the code above will be:
e |
You can add a second parameter to the RegExp object, to specify your search. For example; if you want to find all occurrences of a character, you can use the "g" parameter ("global").
For a complete list of how to modify your search, visit our complete RegExp object reference.
When using the "g" parameter, the exec() method works like this:
var patt1=new RegExp("e","g"); do { result=patt1.exec("The best things in life are free"); document.write(result); } while (result!=null) |
Since there is six "e" letters in the string, the output of the code above will be:
eeeeeenull |
The compile() method is used to change the RegExp.
compile() can change both the search pattern, and add or remove the second parameter.
var patt1=new RegExp("e"); document.write(patt1.test("The best things in life are free")); patt1.compile("d"); document.write(patt1.test("The best things in life are free")); |
Since there is an "e" in the string, but not a "d", the output of the code above will be:
truefalse |
For a complete reference of all the properties and methods that can be used with the RegExp object, go to our complete RegExp object reference.
The reference contains a brief description and examples of use for each
property and method including the string object
From http://www.w3schools.com (Copyright Refsnes Data)