JavaScript RegExp
Object
RegExp: A shorthand for regular expressions.
Complete RegExp Object Reference Manual
Please refer to our JavaScript RegExp Object Reference Manual, which provides all properties and methods that can be used with string objects.
This manual includes detailed descriptions and examples of each property and method.
What is RegExp?
A regular expression describes a pattern of characters.
When you search for some 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.
More complex patterns include more characters and can be used for parsing, format checking, replacement, and more.
You can specify where to search in the string and what type of characters to search for, among other things.
Syntax
- The pattern describes an expression model.
- Modifiers describe whether the search is global, case-sensitive, etc.
Note: When using the constructor to create a RegExp object, you need to follow the usual character escape rules (precede with a backslash ). For example, the following are equivalent:
var re = new RegExp("\\w+");
var re = /\w+/;
RegExp Modifiers
Modifiers are used to perform case-insensitive and global searches.
i - Modifier is used to perform a case-insensitive match.
g - Modifier is used for a global search (instead of stopping at the first match, it finds all matches).
Example 1
Case-insensitive search for "tutorialpro" in a string:
var str = "Visit tutorialpro";
var patt1 = /tutorialpro/i;
The following marked
text is the matched expression: tutorialpro
Example 2
Global search for "is":
var str = "Is this all there is?";
var patt1 = /is/g;
The following marked
text is the matched expression:
Is this all there is?
Example 3
Global and case-insensitive search for "is":
var str = "Is this all there is?";
var patt1 = /is/gi;
The following marked
text is the matched expression:
Is this all there is?
test()
The test() method searches a string for a specified value and returns true or false based on the result.
The following example searches the string for the character "e":
Example
Since the character "e" exists in the string, the output will be:
When using the constructor to create a RegExp object, you need to follow the usual character escape rules (precede with a backslash ).
Example
exec()
The exec() method searches a string for a specified value. It returns the found value or null if no match is found.
The following example searches the string for the character "e":
Example 1
var patt1 = new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
Since the character "e" exists in the string, the output will be:
e