1. Regular expression creation method
// the literal form
console.log(/a/.test(str))

// Form of the object
let reg = new RegExp('h'.'g')
console.log(reg.test(str))
Copy the code
2. Create regular expressions using objects
let con = prompt("Please enter what you want to search for")
let reg = new RegExp(con,'g')
let div = document.querySelector("div")
div.innerHTML = div.innerHTML.replace(reg,search= >{
    return `<span style="color:red">${search}</span>`
})
// Get what the user wants to search for, create a regular expression, global replace, style the data to which the re matches
Copy the code
3. Use of selectors|
/ / | or symbols
let str = 'hello world'
// return true whenever STR contains either a or u
console.log(/a|u/.test(str))

let tel = '010-99999999'
// Start with 010 or 020 followed by 7-8 digits
console.log(010 | / ^ (020) \ - \ {7, 8} $/ d.test(tel))
Copy the code
4. Atom list and atom group selectors[] (a)
// Atom table [] matches one of them e.g. [123] can match 1 or 2 or 3
// Atom group () matches a group of atoms (). For example, (123) means that only 123 matches 1 or 2
Copy the code
5. Escape\
There is a difference between escaping literal and object created regees
let  price = 23.45
// Match one or more. Characters followed by one or more digits
// The. Character, if not escaped, represents everything except the newline character
console.log(/\d+\.\d+/.test(price))

// In creating the re for the object, you need to add an escape to \d, otherwise \d will be parsed into a D letter
let reg = new RegExp('\\d+\\.\\d+')
console.log(reg.test(price))
Copy the code
6. Character boundary constraints^ $
let n = 'baidu2222222baidu'
// Result without character boundaries
console.log(/\d/.test(n))  //true indicates that only numbers are required in the string

// add a character boundary ^ to indicate the beginning and $to indicate the end
console.log(/^\d$/.test(n))  //false matches only one number

// Start with a number
console.log(/^\d/.test(n))

// End with a number
console.log(/\d$/.test(n))

document.querySelector("[name='user']").addEventListener("keyup".function(){
    // Use the function expression used for this instead of the arrow function
    // Start with a letter. The number of letters is between 3-6
    let flag = this.value.match(/ ^ [a-z] {3} /)
    // Return success array on success and null on failure
    document.querySelector("span").innerHTML = flag?"Right":"Failure";
})
Copy the code
7. Numeric and blank metacharacters\d \s
let str = 'hello world 2021'
console.log(str.match(/\d+/g))    / / [2021]

let str2 = 'Zhang SAN :010-11111111, Li Si :020-22222222'
// Get the phone number
console.log(str2.match(/ \ d {3} - \ {7, 8} d/g))
/ / [010-11111111 020-22222222]

// [] ^ is the inverse
// Other than: - numbers, these symbols, only space and Chinese
console.log(str2.match(/[^:-\d,]/g))

// \s resolve Spaces
console.log(str2.match(/[^:-\d,\s]/g))
//[' zhang ',' three ',' Li ',' four ']

// Make the original Chinese together
console.log(str2.match(/[^:-\d\s,]+/g))
//[" zhang SAN "," Li Si "]
Copy the code
8.wCharacters and\wmetacharacters
/ / \ \ w and w
// \w stands for alphanumeric underscore \w everything except alphanumeric underscore
let str = 'helloworld2021'
console.log(str.match(/\w+/))  //helloworld2021

let email = '[email protected]'
console.log(email.match(/^\w+@\w+\.\w+$/))
// '[email protected]'

// Alphanumeric alphanumeric underscores can be 5-10 digits
let username = prompt("Please enter user name")
console.log(/ ^ [a zA - Z] {4, 9} $\ w /.test(username))
Copy the code
  1. .metacharacters
    //. All Spaces except newlines and newlines are two different things
    let str = 'hello world'
    // Matches everything except newlines
    console.log(str.match(+ /. /))
    
    //https:// optional
    let url = 'https://www.baidu.com'
    console.log(url.match(/(https:\/\/)? \w+\.\w+.\w+/))
    
    //s can ignore Spaces
    let str2 =` baidu.com jd.com ` 
    console.log(str2.match(+ /. /s)[0])
    
    // \s 
    let tel = '010-99999999'
    console.log(tel.match(/ \ d {3} - \ d {7, 8} /))
    console.log(tel.match(/ \ d {3} \ s - \ \ {7, 8} d/s))
    Copy the code
  2. Match all characters\s\S \d\D
let str = `  1231 avasdas 3##! %^&* SAGYSUID DSFHAUISDAsdhafuisp God sent iOS ha  '
//. Everything except newline character \d digit \w digit alphanumeric underscore
let str2 = 'ab33333333^^'
// If it is in [], it can be matched
console.log(str2.match(/[ab1234567890^@#$%&*]+/))

// Match all
// [\s\S] [\d\D]
// All of them match
console.log(str.match(/<span>[\s\S]+<\/span>/))
Copy the code
11. Pattern modifier
// I is case insensitive
//g global match
//gi can mix global matching and is case insensitive
let hd = "houdunren"
console.log(hd.match(/u/gi))   //['u','u']

// The global replacement u is @ and case insensitive
console.log(hd.replace(/u/gi.The '@'))   //ho@d@nren
Copy the code
12. Multi-line matching modifier
let str = #1 js, $200 # #2 PHP, $300 # #3 Java, $400 # #4 Node.js, $200 #

[{name:'js',price:'200 yuan '}]
let lessons = str.match(/^\s*#\d+\s*.+\s*#$/gm).map(v= >{
    v = v.replace(/\s*#\d+\s*/.' ').replace(/\s*#/.' ')
    let arr = v.split(', ')
    return {name:arr[0].price:arr[1]}})console.log(lessons)
console.log(JSON.stringify(lessons))
Copy the code
13. Chinese characters and character attributes
/ / Chinese
let hd = 'Houdunren. Keep publishing tutorials'
// Get all words excluding symbols
console.log(hd.match(/\p{L}/gu))
// Get all symbols
console.log(hd.match(/\p{P}/gu))
// Get all the characters
console.log(hd.match(/\p{sc=Han}/gu))

// Use u for wide-body characters
let str = 'Chinese is a broad-body character'
// If you want to match a wide-body word, you must use u
console.log(str.match(/\p{sc=Han}/u))
Copy the code
  1. lastIndexattribute
/ / lastIndex use
// Specifies the starting position of the next match. This property can only be used with the configuration flag G
// The result of the last match was found by the methods regexp.exec () and regexp.test ()
let hd = "houdunren"
let reg = /\w/g
console.log(reg.lastIndex)   / / 0
console.log(reg.exec(hd))  //h 
console.log(reg.lastIndex)  / / 1
console.log(reg.exec(hd))   //o

while((res = reg.exec(hd))){
    console.log(reg.lastIndex) //0-9 nine pop-ups
    console.log(res)  // 'h' , 'o' ,'u'....... 'n' nine separate pops
}
Copy the code
15. Effective Y mode
let hd = "Said the big four Banks and sodium hyposulphite: 11111111222222, 2333333 three loves means is lost is big band sultan hassan www.baidu.com"
let arr = []
//g is suitable when the global data to be retrieved is incoherent
console.log(hd.match(/\d+,? /g))
//['11111111,',' 22222222,',' 33333333']
//y is suitable for local data to be obtained when the coherence is not obtained
let reg = /\d+,? /y
reg.lastIndex = 11   // Set the starting position
while((res = reg.exec(hd))){
    arr.push(res[0])}console.log(arr)
//['11111111,',' 22222222,',' 33333333']
Copy the code
16. Use of atomic tables
let hd = "houdunren"
console.log(hd.match(/[ue]/g))
// ['u','u','e']

// year month day / - symbol split
let date = "2020-02-11"
// The following two re's are actually the same
let reg = /^\d{4}[-/]\d{2}[-/]\d{2}/
let reg = /^\d{4}([-/])\d{2}\1\d{2}/
console.log(date.match(reg))
Copy the code
17. Atom table interval matching
<input type="text" name="username">
<script>
    let num = '2010'
    console.log(num.match(/[0-9]+/g))
    
    let hd = "houdunren"
    console.log(hd.match(/[a-z]+/g))
    
    let input = document.querySelector('[name="username"]')
    input.addEventListener("keyup".function(){
        console.log(this.value.match(/ ^ [a-z] {3, 6} $\ w/I))
        //console.log(/^[a-z]\w+$/i.test(this.valaue))
    })
</script>
Copy the code
18. Eliminate matches
/ / ^ ruled out
let hd = 'houdunren.com'
console.log(hd.match(/[^ue]/gi))
/ / [' h ', 'o', 'd', 'n', 'r', 'n', '. ', 'c', 'o', 'm'] everything except for ue

let str = 'Zhang SAN :010-11111111, Li Si :020-22222222'
// Get the Chinese characters in the string
/ / 1. The elimination process
console.log(str.match(/[^:-\d,]+/g))

/ / 2. Match
console.log(str.match(/\p{sc=Han}+/gu))
Copy the code
19. Atomic table characters are not parsed
// Atomic table characters are not parsed
let hd = '(houdunren).+'
console.log(hd.match(/[.+]/gi))
//['.' , '+']
console.log(hd.match(/[()]/g))
/ / / '(',') '

// The characters in the atomic table are not parsed, but represent the characters themselves
Copy the code
20. Atomic table matches everything
let hd = ` houdunren hdcms `
//s After the use of s the special character dot contains the newline character \n
consol.log(hd.match(/.+/gs))
//['\n houdunren\n hdcms\n ']

//[\s\ s] [\d\ d] indicates all contents
console.log(hd.amtch(/[\s\S]+/) [0])
// houduanren
// HDCMS two data are popped together containing Spaces and newlines
Copy the code
21. Regular expressions manipulate DOM elements
<body>
    <h1>Sponsor education</h1>
    <div> this is houdunren.com</div>
</body>
<script>
    let body = document.body
    let reg = /<(h[1-6])>[\s\S]*<\/\1>/gi
    // Global matching h1-H6 tags can have any data in the middle
    
    // Replacing the above h1 tag with a null character is equivalent to deleting the H1 tag
    body.innerHTML = body.innerHTML.replace(reg,' ')
</script>
Copy the code
22. Know the atomic group
let str = ` 

string1

string2

`
let reg = /<(h[1-6])>[\s\S]*<\/\1>/i console.log(str.match(reg)) // [ 0: "

string

"
// 1: "h1" // 1 stands for what // groups: undefined // group name // index: 13 // start position / / input: "\ n < h1 > string < / h1 > \ n < h2 > string2 < / h2 > \ n" / / the raw data // length: 2] Copy the code
23. Use of mailbox authentication atomic groups
<body>
    <input type="email" name="userEmail">
    <span></spanspan>
</body>
<script>
    let email = document.querySelector(`[name="userEmail"]`)
    emial.addEventListener("keyup".function(){
       let reg = /^[\w-]+@([\w-]+\.) {1, 2} (com | | cn org | cc |.net) $/ I
        document.querySelector("span").innerText = reg.test(this.value)?'right':'failure'
    })
</script>
Copy the code
24. Atomic group reference completes the replacement operation
let hd = ` < h1 > houdunren < / h1 > < span > backing people < / span > < h2 > HDCMS < / h2 > `
let reg = /<(h[1-6])>([\s\S]+)<\/\1>/gi
// The substitution is completed by matching the data that matches the re and then making the substitution
[\s\ s]+ = all the contents of the tag
console.log(hd.replace(reg,`<p>$2</p>`))
// Replace all h1 tags with tags
        // 

houdunren

//

hdcms

let res = hd.replace(reg,(p0,p1,p2) = >{ console.log(p0) // The matched elements are the contents of two H1 / H2 tags console.log(p1) // The contents of the first () inside h1 h2 console.log(p2) // The contents of the second () houdunren HDCMS }) Copy the code
25. Nested and unrecorded grouping
let hd = ` https://www.houdunren.com http://www.baidu.com https://hdcms.com `
let reg = /^https? :\/\/(\w+\.) ? \w+\.(com|cn|org)$/gi
console.dir(hd.match(reg))
        / / /
        // 0: "https://www.houdunren.com"
        // 1: "http://www.baidu.com"
        // 2: "https://hdcms.com"
        // length: 3
        / /]
/ /? : The current group is not recorded
let reg2 = /^https? : \ \ / ((? :\w+\.) ? \w+\.(? :com|cn|org))$/gi
console.dir(hd.match(reg2))

let urls = []
while((res = reg2.exec(hd))){
    urls.push(res[1])}console.log(urls)
Copy the code
26. Basic use of multiple repeat matches
let hd = "hdddddd"
/ / *? + {} Greedy matching pattern
//+ one or more
console.log(hd.match(/hd+/))   // "hdddddd"
/ /? Zero or one
console.log(hd.match(/hd? /))    //"hd"
//* zero one or more
console.log(hd.match(/hd*/))     //"hdddddd"
//{} interval matches as many matches as possible if (1,)
console.log(hd.match(/ hd / {1, 4}))  //"hdddd"
Copy the code
27. Effect of repeated matching on atomic group and phone number regularization
let hd = "hdhdhdhddddddddddddddddddddddddhd"
console.log(hd.match(/hd+/g))
// ['hd', 'hd', 'hd', 'hddddddddd', 'hd']

console.log(hd.match(/(hd)+/g))
// ['hdhdhdhd', 'hd']

// The phone number is regular
let tel = ` 010-99999999 `
console.log(tel.match(/ ^ o \ d {2, 3} - \ d {8 or 9} $/))
Copy the code
28. Verify the user name of the website
<body>
    <input type="text" name="username">
</body>
<script>
    document.querySelector(`[name="username"]`).addEventListener("keyup".function(e){
        let res = e.target.value
        let reg = / ^ [a zA - Z] [/ w] {2, 7} $/
        console.log(reg.test(res))
    })
</script>
Copy the code
29. Use re to verify passwords in batches
<body>
    <input type="text" name="password">
</body>
<script>
    document.querySelector(`[name="password"]`)
        .addEventListener("keyup".e= >{
        let value = e.target.value
        // The password must contain uppercase letters and digits
        const reg = [
            / ^ [a - z0-9] {5, 10} $/ I./[A-Z]/./ [0-9]
        ]
        let state = reg.every(e= >{
            return e.test(value)
        })
        console.log(state)
    })
</script>
Copy the code
Forbid greed
/ /? Ban greed
let hd = `hddddd`
console.log(hd.match(/hd+? /))    //hd
console.log(hd.match(/hd{2,}? /))   //hdd
Copy the code
31. Tag replacement is prohibited for greedy use
<main>
    <! -- Replace span with h4 -->
     <span>123123123</span>
     <span>123123123</span>
     <span>123123123</span>
</main>
<script>
    const main = document.querySelector('main')
    const reg = /([\s\S]+?) <\/span>/gi
    main.innerHTML = main.innerHTML.replace(reg,(v,p1) = >{
        return `<h4 style="color:red;" Word-wrap: break-word! Important;"${p1}</h4>`
    })
</script>
Copy the code
32. Use matchAll for global matching
<body>
    <h1>12312312A</h1>
    <h1>12312312B</h1>
    <h1>12312312C</h1>
</body>
<script>
    let reg = /<(h[1-6])>([\s\S]+?) <\/\1>/gi
    const body = document.body
    const hd = body.innerHTML.matchAll(reg)
    let arr = []
    for(const iterator of hd){
        console.log(iterator)
        arr.push(iterator[2])}console.log(arr)
    // ['12312312A', '12312312B', '12312312C']
</script>
Copy the code
33. Use exec to complete global matching
<body>
    <h1>123123</h1>
    <h1>123123</h1>
    <h1>123123</h1>
</body>
<script>
    let hd = "houdunren"
    let reg = /u/gi
    let result = []
    
    while((res = reg.exec(hd))){
        result.push(res)
    }
    console.log(result)
    
    function search(String,reg){
        let result = []
        while((res = reg.exec(String))){
            result.push(res)
        }
        return result
    }
    let matchs = search(document.body.innerHTML,/<(h[1-6])>([\s\S+?] )<\/\1>/gi)
    console.log(matchs)
</script>
Copy the code
34. String re methods search and match
let hd = "houdunren.com"
//search returns the position where the string to be matched first appears in the string
// Does not return -1
console.log(hd.search(/u/g))
let str = ` https://www.baidu.com http://www.jd.com https://www.sinna.com.cn `
let reg = /^https? :\/\/(www\.) ? (\w+\.) {1, 2} (com) | cn $/ gi
console.log(str.match(reg))
Copy the code
35. String re methods matchAll and split
let hd = ` https://www.baidu.com http://www.jd.com https://www.sinna.com.cn `
let reg = /^https?" \/\/(www\.) ? (\w+\.) +(com|cn)$/gi
for(const iterator of hd.matchAll(reg)){
    console.log(iterator)
}

let time1 = '2020/09/01'
let time2 = '2020-09-12'
console.log(time1.split(/ [- \] / /))
console.log(time2.split(/ [- \] / /))
Copy the code
36. Use of the $symbol in regular substitutions
let tel = '2020/1/11'
console.log(tel.replace(/\//g.The '-'))

let hd = '(010) 99999999 (0201) 88888888'
let reg = / \ [(\ d {3, 4}) \ \ s (\ d {8 or 9})/g
console.log(hd.match(reg))
console.log(hd.replace(reg),"$1 - $2")
/ / 010-99999999 0201-88888888
Copy the code
37 $& use
<main>Online education is an efficient way to learn and education is a lifelong career</main>
<script>
    const main = document.querySelector("body main")
    main.innerHTML = main.innerHTML.replace(/ education/g.`<a href="https://www.baidu.com">$&</a>`                          
     )
    / / $& education
</script>
Copy the code
38. The use of atomic groups in substitution techniques
<main>
        <a style="color:red" href="http://www.hdcms.com">Open source system</a>
        <a href="http://houdunren.com">Backed up by people</a>
        <a href="http://yahoo.com">Yahoo!</a>
        <h4>http://www.hdcms.com</h4>
</main>
<script>
    // need to change to https://www.xxx.com
    const main = document.querySelector("body main")
    let reg = /(.*href=['"])(http)(:\/\/)(www\.) ? (hdcms|houdunre)(\.) (com|cn)/gi
    main.innerHTML = main.innerHTML.replace(reg,(v,... args) = >{
        console.log(v)
        console.log(.. args) args[1] + ='s'   //http += 's'
        args[3] = args[3] | |'www.'    // WWW. Does it exist? Does it not exist
        return args.splice(0.5).join("")})</script>
Copy the code
39. Atomic group name
let hd = ` < h1 > houdunren < / h1 > < span > backing people < / span > < h2 > HDCMS < / h2 > `
const reg = /<(h[1-6])>(.*?) <\/\1>/gi
console.log(hd.replace(reg,`<h4>$2</h4>`))
/ /? 
      
        here is alias
      
const reg2 = /<(h[1-6])>(? 
      
       .*?) <\/\1>/gi
      
console.log(hd.replace(reg2,`<h4>$<con></h4>`))
Copy the code
40. Optimize re using atomic group names
<main>
    <a id="a" href="https://www.baidu1.com">Backed up by people</a>
    <a id="a" href="https://www.baidu2.com">Backed up by people</a>
    <a id="a" href="https://www.baidu3.com">Backed up by people</a>
</main>
<script>
    const main = document.querySelector("main")
    const reg = /
       
        .*?) 1 > \ (? 
        .*?) <\/a>/gi
       *?>
    const links=[]
    for(const iterator of main.innerHTML.matchAll(reg)){
        link.push(iterator['groups'])}console.log(links)
</script>
Copy the code
41. Regular method test
const emial = document.querySelector(`[name="email"]`)
email.addEventListener("keyup".function(e){
    let value = e.target.value
    let reg = /^[\w-]+@([\w]+\.) +(com|cn|cc)$/i
    let flag = reg.test(value)
    console.log(flag)
})
Copy the code
42. Exec
<main>Constructor prototypes are inseparable from constructors</main>
<script>
    let reg = / constructor /g
    const main = document.querySelector("body main")
    let count = 0;
    while((res = reg.exec(main.innerHTML))){
        count++
    }
    console.log(count)
</script>
Copy the code
43. Predicate matching
<main>Sponsors continue to share video tutorials, learning from sponsors to improve programming ability</main>
<script>
    / /? = predicate match
    let main = document.querySelector("body main")
    let regOld = / backer /g
    let reg = / backer (? = tutorials)/g
    main.innerHTML = main.innerHTML.replace(reg,` $& `)
</script>
Copy the code
44. Use assertions to match canonical prices
let lessons = Js, $200,300 hits PHP, $300.00,100 hits Node. js, $180,260 hits
let reg = /(\d+)(.00)? (? =)/gi
lessons = lessons.replace(reg,(v,... args) = >{
    args[1] = args[1] | |00 '. '
    return args.slice(0.2).join("")})console.log(lessons)
Copy the code
45. Predicate match 2
<body>
    <main>
        <a href="https://baidu.com">baidu</a>
        <a href="https://yahoo.com">Yahoo!</a>
    </main>
    <script>
        const main = document.querySelector("main")
        const reg = / (? <=href=["']).+(? =["'])/gi
        main.innerHTML = main.innerHTML.replace(reg,'https://www.houdunren.com')
        
        let hd = "houdunren789hdcms666"
        const reg2 = / (? <=houdunren)\d+/i
        console.log(reg2.test(hd))    // The number must be preceded by the string houdunren
    </script>
</body>
Copy the code
46. Use assertions to match obscure phone numbers
let users = 'Yasuo: 18117098030 backing person: 18717191629
let reg = / (? <=\d{7})\d{4}/gi
users = users.replace(reg,v= >{
    return "*".replace(4)})console.log(users)
Copy the code
47. Predicate matching
let hd = "houdunren2010hdcms"
let reg = /[a-z]+(? ! \d+)$/i
console.log(hd.match(reg))    // HDCMS gets the string segment that is not followed by a number
Copy the code
48. Predicate matching limits user name keywords
<main>
    <input type="text" name="username">
</main>
<script>
    const input = document.querySelector(`[name="username"]`)
    input.addEventListener("keyup".function(){
        / /? ! Not allowed to appear
        // The user name is not allowed.-? Three characters
        const reg = / ^ (? ! . * /. \ \ -? . *) [\ s \ s] {5, 10} $/
        console.log(this.value.match(reg))
        // When the input box contains. -? I get null for three symbols
    })
</script>
Copy the code
49. Predicate matching
let hd = 'hdcms123123houdunren'
// A letter is not preceded by a number
let reg = / (? 
      
console.log(hd.match(reg))
Copy the code
50. Unify data using assertion exclusion
<main>
        <a href="https://www.houdunren.com/1.jpg">1.jpg</a>
        <a href="https://oss.houdunren.com/1.jpg">2.jpg</a>
        <a href="https://cdn.houdunren.com/1.jpg">3.jpg</a>
        <a href="https://houdunren.com/1.jpg">4.jpg</a>
</main>
<script>const main = document.querySelector("main") const reg = /https:\/\/([a-z]+)? (?<! oss)\.. +? (? =\/)/gimain.innerHTML = main.innerHTML.replace(reg,v=>{
        return "https: / /oss.houdunren.com"})</script>
Copy the code