JavaScript regular expressions
- A regular expression is a character sequence of search mode
- Search pattern can be used for text search and replace operation text
Using regular
String Methods
- In JavaScript, regular expression string often use two methods:
Regular grammar
/[搜索模式]/[修饰符]
search()
- search () method to search for matching expression, but also to accept the search string as a parameter and returns the position matching .
Character search search ()
var str = "Huawei" ;
var n = str.search("we");
// 返回 n = 3
Regular use search ()
var str "Huawei" ;
var n = str.search(/we/i) ;
// 返回 n = 3
replace()
Character search replace ()
- All text after text replacement mode, return to replace the search mode
var str = "Huawei,China" ;
var re = str.replace("Huwawei","HUAWEI") ;
// 结果:HUAWEI,China!
Regular use replace ()
var str = "Huawei,China" ;
var re = str.replace(/huawei/i,"HUAWEI") ;
// 结果:HUAWEI,China!
Regular awareness
Regular expression modifiers
i |
Not case sensitive |
g |
Perform a global search match (find all content) |
m |
The implementation of multi-line matching |
Regular expression pattern
[abc] |
Find any character between the brackets |
[0-9] |
Find any number between 0-9 |
(X | y) |
Find any options separated by a vertical bar |
\d |
Find Digital |
\s |
Find a blank character |
\b |
Match a word boundary |
\uxxxx |
Find unicode character specified in hexadecimal xxx |
- The definition of quantifiers
n + |
Matches any string comprising at least one of n |
n * |
Matches any string contains zero or more occurrences of n |
n ? |
Matches any zero or a string containing n |
Using the test ()
- the Test () : a regular expression method
String to search through mode, and returns true or false
var re = /C/;
re.test("China - Huawei");
// 返回 true
/* 简单写 */
/C/.test("China - Huawei");
Use exec ()
- Exec () : a regular expression method
Search by specifying a search pattern string, and returns the searched text (not match returns to the Null)
var re = /C/ ;
re.exec("China - Huawei");
// 返回 C
/*******简写*******/
/C/.exec("China - Huawei");