The Regexp object is used to specify the content to be retrieved in the text.
What is Regexp?
Regexp is the abbreviation of a regular expression.
When you retrieve a text, you can use a mode to describe the content to be retrieved. Regexp is in this mode.
A simple mode can be a single character.
More complex modes include more characters and can be used for parsing, format check, replacement, and so on.
You can specify the search position in the string and the type of characters to be retrieved.
Define Regexp
The Regexp object is used to store the retrieval mode.
Use the New Keyword to define the Regexp object. The following code defines the Regexp object named patt1, and its pattern is "E ":
var patt1=new RegExp("e");
When you use this Regexp object to search in a string, the character "E" will be searched ".
Regexp object Method
The Regexp object has three methods: Test (), exec (), and compile ().
Test ()
The test () method retrieves the specified value in the string. The return value is true or false.
Example:
var patt1=new RegExp("e");document.write(patt1.test("The best things in life are free"));
Because the character string contains the letter "E", the output of the above Code will be:
true
Tiy
Exec ()
The Exec () method retrieves the specified value in the string. The returned value is the value found. If no matching is found, null is returned.
Example 1:
var patt1=new RegExp("e");document.write(patt1.exec("The best things in life are free"));
Because the character string contains the letter "E", the output of the above Code will be:
e
Tiy
Example 2:
You can add the second parameter to the Regexp object to set the search. For example, you can use the "G" parameter ("Global") if you want to find all the characters that exist ").
For complete information on how to modify the search mode, visit our Regexp object reference manual.
When the "G" parameter is used, exec () works as follows:
- Locate the first "E" and store its location
- If exec () is run again, search from the storage location, find the next "E", and store its location
var patt1=new RegExp("e","g");do{result=patt1.exec("The best things in life are free");document.write(result);}while (result!=null)
The code output will be:
eeeeeenull
Tiy
Compile ()
The compile () method is used to change Regexp.
Compile () can either change the search mode or add or delete the second parameter.
Example:
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"));
The output of the above Code is:
truefalse
Tiy
Complete Regexp Object Reference Manual
To use complete information about all the attributes and methods with the Regexp object, visit our Regexp object reference manual.
This reference manual contains a detailed description of each attribute and method in the Regexp object, as well as examples of use.