Table of contents
- 1. Summary
- 2. Syntax
- 3. Parameters
- 4. Description
- 5. Properties
- 6. Methods
- 7. RegExp instances
- 7.1. Properties
- 7.2. Methods
- 8. Examples
- 9. Browser compatibility
- 10. See also
Summary
Creates a regular expression object for matching text with a pattern.
Syntax
RegExp(pattern [, flags])
/pattern/flags
Parameters
pattern- The text of the regular expression.
flags
If specified, flags can have any combination of the following values:
g- global match
i- ignore case
m- Treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
y-
New in Firefox 3
Non-standard
sticky; matches only from the index indicated by thelastIndexproperty of this regular expression in the target string (and does not attempt to match from any later indexes). This allows the match-only-at-start capabilities of the character "^" to effectively be used at any location in a string by changing the value of thelastIndexproperty.
Description
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:
var re = new RegExp("\\w+");
var re = /\w+/;
Notice that the parameters to the literal format do not use quotation marks to indicate strings, while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:
/ab+c/i;
new RegExp("ab+c", "i");
Special characters in regular expressions
| Character | Meaning |
\ | For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally. For example, or For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally. For example, * is a special character that means 0 or more occurrences of the preceding character should be matched; for example, |
^ | Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character. For example, |
$ | Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character. For example, |
* | Matches the preceding item 0 or more times. For example, |
+ | Matches the preceding item 1 or more times. Equivalent to For example, |
? | Matches the preceding item 0 or 1 time. For example, If used immediately after any of the quantifiers Also used in lookahead assertions, described under |
. | (The decimal point) matches any single character except the newline characters: \n \r \u2028 or \u2029. ( For example, |
(x) | Matches For example, |
(?:x) | Matches |
x(?=y) | Matches |
x(?!y) | Matches
|
x|y | Matches either For example, |
{n} | Where For example, |
{n,} | Where For example, |
{n,m} | Where For example, |
[xyz] | A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen. For example, |
[^xyz] | A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen. For example, |
[\b] | Matches a backspace. (Not to be confused with |
\b | Matches a word boundary, such as a space. (Not to be confused with For example, |
\B | Matches a non-word boundary. For example, |
\cX | Where For example, |
\d | Matches a digit character in the basic Latin alphabet. Equivalent to Note: In Firefox 2 and earlier, matches a digit character from any alphabet. ( bug 378738 ) For example, |
\D | Matches any character that is not a digit in the basic Latin alphabet. Equivalent to Note: In Firefox 2 and earlier, excludes digit characters from all alphabets. ( bug 378738 ) For example, |
\f | Matches a form-feed. |
\n | Matches a linefeed. |
\r | Matches a carriage return. |
\s | Matches a single white space character, including space, tab, form feed, line feed and other unicode spaces. Equivalent to [ \t\r\n]. For example, |
\S | Matches a single character other than white space (Not whitespace). Equivalent to For example, |
\t | Matches a tab. |
\v | Matches a vertical tab. |
\w | Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to For example, |
\W | Matches any character that is not a word character from the basic Latin alphabet. Equivalent to For example, |
\n | Where For example, |
\0 | Matches a NUL character. Do not follow this with another digit. |
\xhh | Matches the character with the code |
\uhhhh | Matches the character with the Unicode value |
The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.
The constructor of the regular expression object, for example, new RegExp("ab+c"), provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
Properties
For properties available on RegExp instances, see Properties of RegExp instances.
- prototype
- Allows the addition of properties to all objects.
Methods
For methods available on RegExp instances, see Methods of RegExp instances.
The global RegExp object has no methods of its own, however, it does inherit some methods through the prototype chain.
RegExp instances
Properties
See also Deprecated RegExp Properties
Note that several of the RegExp properties have both long and short (Perl-like) names. Both names always refer to the same value. Perl is the programming language from which JavaScript modeled its regular expressions.
constructor- Specifies the function that creates an object's prototype.
global- Whether to test the regular expression against all possible matches in a string, or only against the first.
ignoreCase- Whether to ignore case while attempting a match in a string.
lastIndex- The index at which to start the next match.
multiline- Whether or not to search in strings across multiple lines.
source- The text of the pattern.
sticky- New in Firefox 3 Non-standard
- Whether or not the search is sticky.
Methods
- See also Deprecated RegExp Methods
exec- Executes a search for a match in its string parameter.
test- Tests for a match in its string parameter.
toSource- Non-standard
Returns an object literal representing the specified object; you can use this value to create a new object. Overrides theObject.prototype.toSourcemethod. - toString
- Returns a string representing the specified object. Overrides the
Object.prototype.toStringmethod.
Object:__defineGetter__, __defineSetter__, hasOwnProperty, isPrototypeOf, __lookupGetter__, __lookupSetter__, __noSuchMethod__, propertyIsEnumerable, toLocaleString, unwatch, valueOf, watch
Examples
Example: Using a regular expression to change data format
The following script uses the replace method inherited by the String instance to match a name in the format first last and output it in the format last, first. In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.
var re = /(\w+)\s(\w+)/; var str = "John Smith"; var newstr = str.replace(re, "$2, $1"); print(newstr);
This displays "Smith, John".
Example: Using a regular expression with the "sticky" flag
This example demonstrates how one could use the sticky flag on regular expressions to match individual lines of multiline input.
var text = "First line\nsecond line"; var regex = /(\S+) line\n?/y; var match = regex.exec(text); print(match[1]); // prints "First" print(regex.lastIndex); // prints 11 var match2 = regex.exec(text); print(match2[1]); // prints "Second" print(regex.lastIndex); // prints "22" var match3 = regex.exec(text); print(match3 === null); // prints "true"
One can test at run-time whether the sticky flag is supported, using try { … } catch { … }. For this, either an eval(…) expression or the RegExp(regex-string, flags-string) syntax must be used (since the /regex/flags notation is processed at compile-time, so throws an exception before the catch block is encountered). For example:
var supports_sticky;
try { RegExp('','y'); supports_sticky = true; }
catch(e) { supports_sticky = false; }
alert(supports_sticky); // alerts "false" in Firefox 2, "true" in Firefox 3+
Example: Regular expression and Unicode characters
As mentioned above, \w or \W only matches ASCII based characters; for example, 'a' to 'z', 'A' to 'Z', 0 to 9 and '_'. To match characters from other languagessuch as Cyrillic or Hebrew, use \uhhhh., where "hhhh" is the character's Unicode value in hexadecimal. This example demonstrates how one can separate out Unicode characters from a word.
var text = "Образец text на русском языке"; var regex = /[\u0400-\u04FF]+/g; var match = regex.exec(text); print(match[1]); // prints "Образец" print(regex.lastIndex); // prints "7" var match2 = regex.exec(text); print(match2[1]); // prints "на" [did not print "text"] print(regex.lastIndex); // prints "15" // and so on
Here's an external resource for getting the complete Unicode block range for different scripts: Regexp-unicode-block
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support | ? | (Yes) | ? | ? | ? |
| Feature | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | ? | (Yes) | ? | ? | ? |
See also
- Regular Expressions chapter in the JavaScript Guide
Mozilla Developer Network