小编今天和大家继续研究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"]]
大家还可以扫描二维码,关注我的微信公众号,蜗牛全栈
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。