preface

When we write front-end forms, when we encounter some fields such as mobile phone number, phone number, email address, ID number and so on, which need to be verified in a certain format, we usually need to define some rules, and then we need to use regular expressions. Before I was baidu search regular expression, and then copy and paste, fix ~ is not very cool. It’s just that regular expressions are cumbersome to write, have more rules, and are readily available online. But requirements will always change, understand their rules correctly, and use them easily.

An overview of the

Yuan string

qualifiers

parameter

Other characters

Give me some chestnuts

Mobile phone number

var pattern = /0? 18 (13 14 15 | | | | 17) [0-9] {9} /; var right = '13265456162'; var err = '11123224332'; console.log(pattern.test(right)); //true console.log(pattern.test(err)); //falseCopy the code

email

var pattern = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+.) + [A Za - z] {2, 14} /; var rightEmail = '[email protected]'; var errEmail = '112@dcom'; console.log(pattern.test(rightEmail)); //true console.log(pattern.test(errEmail)); //falseCopy the code

Id card

var pattern = /^\d{6}(18|19|20)? \d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/; var right = '110101199003078398'; var err = '4452211991123265554'; console.log(pattern.test(right)); //true console.log(pattern.test(err)); //falseCopy the code

Capture group

In addition to verifying that some strings conform to rules, regular expressions can also be used to extract them. Add the concept of capture groups.

Capture group? This is the part of the regular expression enclosed in parentheses. We can do both “match” and “extract” by writing regular expressions like this: