- 以一个简单的例子让人粗浅的理解断言,详细的理解断言可以看这篇博客https://www.cnblogs.com/whaozl/p/5462865.html
- 灵活运用断言可以匹配到你想要的子字符串,要求有较好的正则基础知识
let str = '我爱你,你爱我'
// ?= 先行断言 匹配后面是 我 的爱
let reg = /爱(?=我)/
// ?! 先行否定断言 匹配后面不是 我 的爱
let reg1 = /爱(?!我)/
// ?<= 后行断言 匹配前面是 我 的爱
let reg2 = /(?<=我)爱/
// ?<! 后行否定断言 匹配前面不是 我 的爱
let reg3 = /(?<!我)爱/
//将匹配到的爱换成空白,输出str
console.log(str.replace(reg,' ')); // 输出 我爱你,你 我
console.log(str.replace(reg1,' '));// 输出 我 你,你爱我
console.log(str.replace(reg2,' '));// 输出 我 你,你爱我
console.log(str.replace(reg3,' '));// 输出 我爱你,你 我
Note:更多的时候我们可以将先行断言和后行断言一起使用,既限制前面又限制后面