小编明天和大家持续钻研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"]]
大家还能够扫描二维码,关注我的微信公众号,蜗牛全栈
发表回复