正则匹配替换字符串

记录一下,正则匹配字符串

例:

let a = 'asdf1234<a href="http://www.baidu.com">百度</a>qwer5678<a class="123" href="http://www.google.com">google</a>'

现在要给所有a标签,都加上target="_blank"来让他用新窗口打开

想了一下,基础版写法:

a.replace(/<a/, '<a target="_blank"') // 结果: 'asdf1234<a target="_blank" href="http://www.baidu.com">百度</a>qwer5678<a class="123" href="http://www.google.com">google</a>'

转过头一想,如果字符串中有<a出现,不是代表a标签的意思,那按照上面的正则,一样能匹配到,这种情况该怎么办

在mdn上看了下replace的用法,发现有个 $ ,看了下,没大看明白...

试了下用法,还不错

a.replace(/>(.*?<\/a>)/g, ' target="_blank">$1') // 结果:'asdf1234<a href="http://www.baidu.com" target="_blank">百度</a>qwer5678<a class="123" href="http://www.google.com" target="_blank">google</a>'

相当于正则内的尖角号后面的()内容部分,当成一个整体,替换的时候用$1来代替,使后半部分不变

感兴趣的可以去看下replace的参数设计   https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace

posted @ 2022-09-19 11:19  程序员笔记--vue  阅读(577)  评论(0编辑  收藏  举报