JavaScript regular expressions



Regular Expression (English: Regular Expression, often abbreviated as regex, regexp or RE in code) uses a single string to describe and match a series of string search patterns that conform to a certain syntactic rule.

Search mode can be used for text search and text replacement.


What is a regular expression?

Regular expression is a search pattern formed by a sequence of characters.

When you search for data in text, you can use search patterns to describe what you want to query.

A regular expression can be a simple character, or a more complex pattern.

Regular expressions can be used for all text search and text replacement operations.

grammar

/pattern/modifiers;

Example:

var patt = /php/i

Example analysis:

/php/i is a regular expression.

php is a pattern (used for retrieval).

i is a modifier (search is not case sensitive).


Using string methods

In JavaScript, regular expressions are usually used in two string methods: search() and replace().

search() method is used to retrieve a specified substring in a string, or retrieve a substring that matches a regular expression, and returns the starting position of the substring.

replace() method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.


The search() method uses regular expressions

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<p>搜索字符串 "php", 并显示匹配的起始位置:</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction() {
    var str = "Visit php!"; 
    var n = str.search(/php/i);
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

Running instance»

Click the "Run Instance" button to view the online instance


The search() method uses a string

The search method can use a string as a parameter. String parameters will be converted to regular expressions:

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<p>搜索字符串 "php", 并显示匹配的起始位置:</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction() {
    var str = "Visit php!"; 
    var n = str.search("php");
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

Run Instance»

Click "Run Instance" Button to view online examples



replace() method uses regular expressions

Examples

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php</title>
</head>
<body>

<p>替换 "microsoft" 为 php" :</p>
<button onclick="myFunction()">点我</button>
<p id="demo">请访问 Microsoft!</p>
<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var txt = str.replace(/microsoft/i,"php");
    document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

Run instance»

Click the "Run instance" button to view the online instance


replace() method usage String

replace() method will receive the string as parameter:

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<p>替换 "Microsoft" 为 "php" :</p>
<button onclick="myFunction()">点我</button>
<p id="demo">请访问 Microsoft!</p>
<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var txt = str.replace("Microsoft","php");
    document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance


Did you notice?


NoteRegular expression parameters can be used in the above methods (instead of string parameters).
Regular expressions make the search function more powerful (such as case-insensitive in the example).



Regular expression modifier

Modifier can be searched globally Case insensitive:

ModifierDescription
iExecution Case-insensitive matching.
gPerform global matching (find all matches instead of stopping after the first match is found).
mPerform multi-line matching.



Regular expression pattern

Square brackets are used to find characters within a range:

ExpressionDescription
[abc]Find between square brackets any character.
[0-9]Find any number from 0 to 9.
(x|y)Find any options separated by |.

Metacharacters are characters with special meanings:

MetacharactersDescription
\dFind numbers.
\sFind whitespace characters.
\b Matches word boundaries.
\uxxxxFinds the Unicode character specified as the hexadecimal number xxxx.

Quantifier:

QuantifierDescription
n+ matches any string containing at least one n.
n* Matches any string containing zero or more n.
n? Matches any string containing zero or one n.



Using the RegExp object

In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.


Use test()

The test() method is a regular expression method.

The test() method is used to detect whether a string matches a certain pattern. If the string contains matching text, it returns true, otherwise it returns false.

The following example is used to search for the character "e" in a string:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<script>
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
</script>

</body>
</html>

Run Example»

Click the "Run Instance" button to view the online instance


Use exec()

The exec() method is a regular expression method.

The exec() method is used to retrieve matches of a regular expression in a string.

This function returns an array, which stores the matching results. If no match is found, the return value is null.

The following example is used to search for the letter "e" in a string:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<script>
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
</script>

</body>
</html>

Run Example»

Click the "Run Example" button to view the online example


Complete RegExp reference manual

For complete RegExp object reference manual, please refer to our JavaScript RegExp Reference book.

This reference manual contains all methods and properties of the RegExp object.