Home > Article > Web Front-end > How to write regular expressions in js
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.
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
/正则表达式主体/修饰符(可选)
The modifier is optional.
In JavaScript, regular expressions are commonly used in 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:
Search for "php" string using regular expressions , and is not case-sensitive:
var str = "Visit php!"; var n = str.search(/php/i);
The output result is:
6
The search() method uses the string
The search method can take a string as parameter. String parameters will be converted into regular expressions:
Example: Retrieve the substring of "php" in the string:
var str = "Visit php!"; var n = str.search("php");
replace() method uses regular expressions
Example: Use regular expressions and case-insensitive to replace Microsoft in the string with Runoob:
var str = document.getElementById("demo").innerHTML; var txt = str.replace(/microsoft/i,"php");
The result output is:
Visit php!
replace() method uses string
replace() method will receive string as parameter:
var str = document.getElementById("demo").innerHTML; var txt = str.replace("Microsoft","php");
The above is the detailed content of How to write regular expressions in js. For more information, please follow other related articles on the PHP Chinese website!