JavaScript regular expressions Discussion

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:
    • search()
    • replace()

Regular grammar

/[搜索模式]/[修饰符]
  • search () method to search for matching expression, but also to accept the search string as a parameter and returns the position matching .
var str = "Huawei" ; 
var n = str.search("we");
// 返回 n = 3 
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

Modifiers description
i Not case sensitive
g Perform a global search match (find all content)
m The implementation of multi-line matching

Regular expression pattern

  • expression
expression description
[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
  • Metacharacters
Metacharacters description
\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
quantifier description
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");

Guess you like

Origin www.cnblogs.com/wangyuyang1016/p/11070074.html