JavaScript regu...LOGIN

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?

A 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.

Syntax

/pattern/modifiers;

Example:

var patt = /phpl/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 with two string methods: search() and replace().

search() method is used to retrieve a specified substring in a string, or to 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.


search() method uses regular expressions

Example

Use regular expressions to search for the "php.cn" string, and it is not case-sensitive:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>PHP中文网(php.cn)</title>
</head>
<body>
<p>搜索字符串 "php.cn", 并显示匹配的起始位置:</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
    function myFunction() {
        var str = "Visit php.cn!";
        var n = str.search(/php.cn/i);
        document.getElementById("demo").innerHTML = n;
    }
</script>
</body>
</html>

Run the program and try it


##search( ) method takes a string

# The search method can take a string as a parameter. The string parameters will be converted into regular expressions:

Example

Retrieve the substring of "php.cn" in the string:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>PHP中文网(php.cn)</title>
</head>
<body>
<p>搜索字符串 "php.cn", 并显示匹配的起始位置:</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
    function myFunction() {
        var str = "Visit php.cn!";
        var n = str.search("php.cn");
        document.getElementById("demo").innerHTML = n;
    }
</script>
</body>
</html>

Run the program and try it


replace() method uses regular expressions

Example

Use regular expressions and case-insensitive to replace Microsoft in the string with php.cn:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>PHP中文网(php.cn)</title>
</head>
<body>
<p>替换 "microsoft" 为 "php.cn" :</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.cn");
        document.getElementById("demo").innerHTML = txt;
    }
</script>
</body>
</html>

Run the program and try it


replace() method uses a string

replace() method will receive a string as a parameter:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP中文网(php.cn)</title>
</head>
<body>
<p>替换 "Microsoft" 为 "php.cn" :</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.cn");
    document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>

Run the program to try


Tips:

Regular expression parameters can be used in the above method (replacing string parameters).

Regular expressions make the search function more powerful (such as case-insensitive in the example).


Regular expression modifiers

Modifiers can be case-insensitive in global searches:

Modifier DescriptioniPerforms a case-insensitive match. 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 any characters between square brackets.
[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:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>PHP中文网(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 the program to try it


You don’t need to set the regular expression variable, the above Two lines of code can be combined into one:

/e/.test("The best things in life are free!")


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 in which the matching results are stored. If no match is found, the return value is null.

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

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>PHP中文网(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 the program to try it



Next Section
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PHP中文网(php.cn)</title> </head> <body> <p>搜索字符串 "php.cn", 并显示匹配的起始位置:</p> <button onclick="myFunction()">点我</button> <p id="demo"></p> <script> function myFunction() { var str = "Visit php.cn!"; var n = str.search(/php.cn/i); document.getElementById("demo").innerHTML = n; } </script> </body> </html>
submitReset Code
ChapterCourseware