Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
ES系列文章
ES11 字符串扩展
全局模式捕获:Sting.prototype.matchAll()
const str = `
<html>
<body>
<div>第一个div</div>
<p>这是p</p>
<div>第二个div</div>
<span>这是span</span>
<div>第三个div</div>
</body>
</html>
`
RegExp.prototype.exec() 与 /g
如果正则表达式有/g标志,那么多次调用.exec()就会得到所有匹配的结果。如果没有匹配的结果,.exec()就会返回null。在这之前会返回每个匹配的匹配对象。这个对象包含捕获的子字符串和更多信息。
// exec g
function selectDiv(regExp, str){
let matches = []
while(true){
// console.log(regExp.lastIndex)
const match = regExp.exec(str)
// console.log(match)
if(match == null){
break
}
matches.push(match[1])
}
return matches
}
const regExp = /<div>(.*)<\/div>/g
// const res = selectDiv(regExp, str)
// console.log(res)
String.prototype.match() 与 /g
可以使用.match()方法和一个带有/g标志的正则表达式,你就可以得到一个数组,包含所有匹配的结果(换句话说,所有捕获组都将被忽略)。
// match
console.log(str.match(regExp))
String.prototype.replace() 与 /g
你可以用一个小技巧来收集所有的捕获组——通过.replace()。replace函数接收一个能够返回要替换的值的函数,这个函数能够接收所有的捕获信息。但是,我们不用这个函数去计算替换的值,而是在函数里用一个数组去收集感兴趣的数据。
// replace
function selectDiv(regExp, str){
let matches = []
str.replace(regExp, (all, first) => {
matches.push(first)
})
return matches
}
const res = selectDiv(regExp, str)
console.log(res)
String.prototype.matchAll 方法
// matchAll
function selectDiv(regExp, str){
let matches = []
for(let match of str.matchAll(regExp)){
matches.push(match[1])
}
return matches
}
const res = selectDiv(regExp, str)
console.log(res)
/g作用因为正则表达式有一个lastIndex(初始值为0)属性,每次.exec()前,都会根据lastIndex属性的值来决定开始匹配的位置。如果正则表达式没有/g标志,那么运行一次.exec()时,不会改变lastIndex的值,导致下一次运行exec()时,匹配仍旧是从字符串0的位置开始。当正则表达式加了/g标志后,运行一次exec(),正则表达式的lastIndex就会改变,下次运行exec()就会从前一次的结果之后开始匹配。
不过如果没有使用 /g 的正则模式,.match 的效果和 RegExp.prototype.exec() 是一致的。
一个前端小白,若文章有错误内容,欢迎大佬指点讨论!ES系列 |