JavaScript Regular Expressions and Their Use

JavaScript Regular Expressions and Their Use

1. Creation and Detection of Regular Expressions

(1) Regular expressions are objects that describe character patterns;
Example: Two ways to create regular expressions:

var re = /136[0-9]{8}/;
var re = new RegExp(/136[0-9]{8}/); 

(2) Writing rules: content, number of times

var exp = /a{3}[0-9]+[a-c]{7}/

(3) test(): detects whether the string is a regular expression and returns true or false;


(4) exec(): Retrieves the specified value in the string.The return value is the value found.If no match is found, null is returned

2. Contents of Regular Expressions

(1) Atomic table

atom Explain
[] Match only one atom
[^] Match only any atom except one of its characters
[0-9] Match any number of 0-9
[a-z] Match any lowercase a-z letter
[A-Z] Match any letter of capital A-Z

\d = [0-9]

(2) Metacharacters:

Metacharacter Explain
\w All letters, numbers, underscores
\W All non-numbers, letters, underscores
\d All numbers
\D All Non-Numbers
\s All blank characters, line breaks, spaces, etc.
\S All non-whitespace characters
. Any character except line break

(3) Pattern modifiers:

Modifier Explain
i Case insensitive
g Global Matching
y Match from lastIndex
u Processing UTF-16 encoded characters
m Multiline processing
s Single line processing, ignoring line breaks

Note: You can use i or G alone or at the same time; at the same time, the format can be either i g or G i.


var s1 = 'wom field JHDIOH They oijios Hmm fHus yes idoofi I';
var x1 = s1.match(/[a-z]{1,}/ig);
//["wom", "JHDIOH", "oijios", "fHus", "idoofi"]
var x2 = s1.match(/[a-z]{1,}/gi);
//["wom", "JHDIOH", "oijios", "fHus", "idoofi"]

(4) Atomic group: wrapped in ()
Reference grouping: Reference to the content matched by the previous atomic group;
Group Alias: Name different groups, use? <>Name, use $<>Reference;

        let str = 'abc123.c123'
        let reg = /([a-z]\d+)\.\1/g
        // ["c123.123"]
        let reg1 = /(?<init>[a-z]\d+)\.\1/g
        // console.log(str.match(reg));
        console.log(str.replace(reg1, `<p>$<init></p>`));

(5) Repetition:

Symbol Explain
+ Repeat one or more times
* Repeat zero or more times
? Repeat zero or once
{n} Repeat n times
{n,} Repeat n or more times
{n,m} Repeat n to m times


        let str = '1234'
        let reg = /\d/
        let reg2 = /\d+/
        let reg3 = /^\d{1,2}$/

(6) Character method:

Method Explain
search() Returns the index of the content to be searched, or -1 if not
match() Use string or regular expression matching to return matches or null if no matches are found
matchAll() Return an Iterable Object
replace() Use character to separate strings
split() Replace string with new string


        let str = 'abcdef'
        console.log('ef'));  // 4
        console.log(\w/));  // 0
        console.log('efg'));  // -1
        console.log(str.match('ef'));  // ef
        console.log(str.match(/\w+/));  // abcdef
        let str1 = 'abc/def/123'
        console.log(str1.split('/'));// ["abc","def","123"]
        console.log(str1.replace(/\W/g, '-'));// abc-def-123

(7) Selector:
'|': true if the left and right sides match one
Escape character:'\'


        let str = 'Zhang San: 010-1568413´╝îLi Si: 020-1586640'
        let reg = /(010|020)\-\d{7,8}/
        console.log(reg.test(str)); // true

(8) Boundary: Start with ^ and end with $, which can be used to detect the beginning of web addresses and file suffixes


        let str = ''
        let reg = /^https?:www\..+/
        console.log(reg.test(str));  // true
        let str1 = 'C://Users/All Users/abc.txt'
        let str2 = 'C://Users/All Users/abc.log'
        let reg1 = /\.txt$/
        console.log(reg1.test(str1));  // true
        console.log(reg1.test(str2));  // false

(9) Regular expressions commonly used:

  • 1) User name and password strength:
        //Regular user name, 4 to 16 digits (letters, numbers, underscores, minus signs)
        var uPattern = /^[a-zA-Z0-9_-]{4,16}$/;
        //Output true
        //Regular password strength, minimum of 6 bits, including at least 1 capital letter, 1 lowercase letter, 1 number, 1 special character
        var pPattern = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/;
        //Output true
        console.log("==" + pPattern.test("iFat3#"));
  • 2) Integer:
        //Positive Integer Regular
        var posPattern = /^\d+$/;
        //Negative Integer Regular
        var negPattern = /^-\d+$/;
        //Integer Regular
        var intPattern = /^-?\d+$/;
        //Output true
        //Output true
        //Output true
  • 3) Numbers:
        //Positive Regular
        var posPattern = /^\d*\.?\d+$/;
        //Negative Regular
        var negPattern = /^-\d*\.?\d+$/;
        //Number Regular
        var numPattern = /^-?\d*\.?\d+$/;
  • 4)Email:
        var ePattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        //Output true
  • 5) Mobile number:
        var mPattern = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;
        //Output true
  • 6) ID number:
        var cP = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
        //Output true
  • 7)URL:
        var urlP = /^((https?|ftp|file):\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
        //Output true
  • 8) ipv4 address:
        var ipP = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
        //Output true
  • 9) Hexadecimal color:
        var cPattern = /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;
        //Output true

 - 10)Date: Simple decision,No decision on month and date

        var dP1 = /^\d{4}(\-)\d{1,2}\1\d{1,2}$/;
        //Output true
        //Output true
        //Regular Date, Complex Decision
        var dP2 = /^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$/;
        //Output true
        //Output false
        //Output false
  • 11) QQ number: 5 to 11 digits
        var qqPattern = /^[1-9][0-9]{4,10}$/;
        //Output true
  • 12) Microsignal:
    6 to 20 digits, starting with a letter, letters, numbers, minus signs, underscores
        var wxPattern = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/;
        //Output true
  • 13) License plate number:
        var cPattern = /^[Envoy of Beijing, Tianjin, Shanghai, Yu, Ji, Yun, Liao, Black, Hunan, Anhui, Anhui, New Su, Zhejiang, Gan, Gan, Jin, Shaanxi, Fujian, Gui, Guangdong, Qing, Tibet, Chuan, Ningqiong A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9 Hang Xue Police Hong Kong Macao]{1}$/;
        //Output true
        console.log(cPattern.test("Beijing K39006"));
  • 14) The string contains Chinese:
        var cnPattern = /[\u4E00-\u9FA5]/;
        //Output true
        console.log(cnPattern.test("42 degree"));

(10) Comprehensive application

Example: Remove the array of numbers from the expression string:

        var m = '12+23+45-2*5=70';
        //Remove the number from m
        var n = m.split(/[\+\-\*\/=]/);
        console.log(n);//["12", "23", "45", "2", "5", "70"]

Tags: Javascript Mobile ftp

Posted on Mon, 22 Jun 2020 21:48:13 -0400 by Kevin3374