关于javascript:ES11中matchAll

22次阅读

共计 1751 个字符,预计需要花费 5 分钟才能阅读完成。

小编明天和大家持续钻研 es11,明天的这个办法次要是针对字符串匹配上,之前匹配字符串的时候,更多的是应用正则表达式,就像这样。

const str = `
    <html>
        <body>
            <div> 第一个 div</div>
            <p> 这是个 p </p>
            <div> 第二个 div</div>
            <span> 这是个 span</span>
        </body>
    </html>
`
// 正则表达式中的 exec g
function selectDiv(regExp,str){let matches = []
    while(true){const match = regExp.exec(str)
        if(match  == null){break;}
        matches.push(match) // 如果只想匹配匹配内容,能够写成 matches.push(match[1])
    }
    return matches
}
const regExp  = /<div>(.*)<\/div>/g    // 如果不写 g。会陷入死循环,因为每一次从结尾开始匹配,不能 break
const res = selectDiv(regExp,str)
console.log(res) // [["<div> 第一个 div</div>","第一个 div"],["<div> 第二个 div</div>","第二个 div"]]

下面是通过正则表达式中的 exec 匹配出 html 字符串中的 div 中的内容,针对这个需要,同样能够字符串办法 match 实现,就像这样。然而通过 match,只可能匹配出与正则匹配的字符串,而不能匹配出 div 两头的内容。

const str = `
    <html>
        <body>
            <div> 第一个 div</div>
            <p> 这是个 p </p>
            <div> 第二个 div</div>
            <span> 这是个 span</span>
        </body>
    </html>
    `
const regExp  = /<div>(.*)<\/div>/g
console.log(str.match(regExp) // ["<div> 第一个 div</div>","<div> 第二个 div</div>"]

同样,咱们也能够通过 replace 办法实现,之前应用 replace 办法,只是用于字符串替换,就像这样

let str1 = "aabbcc"
const res = str1.replace(/a/g,b) // bbbbcc

明天咱们来理解这个办法的高级用法,也就是第二个参数传递是个函数,就像这样

function selectDiv(regExp,str){let matches= []
    str.replace(regExp,(all,first) => {matches.push(first)
    }) // 之前用一个要替换的字符串 
    return matches
}
const str = `
    <html>
        <body>
            <div> 第一个 div</div>
            <p> 这是个 p </p>
            <div> 第二个 div</div>
            <span> 这是个 span</span>
        </body>
    </html>
    `
const regExp  = /<div>(.*)<\/div>/g
const res  = selectDiv(regExp,str)
console.log(res) // ["第一个 div","第二个 div"]

当初,让咱们请出明天的配角,matchAll,实例就像这样

function selectDiv(regExp,str){let matches= []
    for(let match of str.matchAll(regExp)){matches.push(match)
    }
    return matches
}
const str = `
    <html>
        <body>
            <div> 第一个 div</div>
            <p> 这是个 p </p>
            <div> 第二个 div</div>
            <span> 这是个 span</span>
        </body>
    </html>
    `
const regExp  = /<div>(.*)<\/div>/g // 如果正则表达式的时候,不写 /g,matchAll 办法会报错
const res  = selectDiv(regExp,str)
console.log(res) // [["<div> 第一个 div</div>","第一个 div"],["<div> 第二个 div</div>","第二个 div"]]

大家还能够扫描二维码,关注我的微信公众号,蜗牛全栈

正文完
 0