-
?=
后面是什么
let str = `蒹葭苍苍,白露为霜。蒹葭萋萋,白露未晞`;
let reg = /蒹葭/g;
console.log(str.replace(reg, `<a href="http://www.baidu.com">$&</a>`));
// <a href="http://www.baidu.com">蒹葭</a>苍苍,白露为霜。<a href="http://www.baidu.com">蒹葭</a>萋萋,白露未晞
下例多了一个?=
,表示条件,只匹配蒹葭后面是萋萋的蒹葭
let str = `蒹葭苍苍,白露为霜。蒹葭萋萋,白露未晞`;
let reg = /蒹葭(?=萋萋)/g;
console.log(str.replace(reg, `<a href="http://www.baidu.com">$&</a>`));
// 蒹葭苍苍,白露为霜。<a href="http://www.baidu.com">蒹葭</a>萋萋,白露未晞
let str = `
包子,2元,2个,4元
酸奶,12.48元,1瓶
饼干,5元,3袋
`;
let reg = /(\d+)(\.\d+)?(?=元,)/g;
console.log(
str.replace(reg, (...arg) => {
console.log(arg);
arg[2] = arg[2] || ".00";
return arg.slice(1, 3).join("") + "元";
})
);
/**
* 包子,2.00元,2个
* 酸奶,12.48元,1瓶
* 饼干,5.00元,3袋
*/
-
?<=
前面是什么
let str = `JonSnowCerceiSnow`;
let reg = /(?<=Jon)Snow/g;
console.log(str.match(reg)); // ["Snow"]
匹配前面是href="
,后面是"
let str = `
<a href="http://baidu.com">百度</a>
<a href="http://google.com">谷歌</a>
`;
let reg = /(?<=href=(["'])).+(?=\1)/g;
console.log(str.replace(reg, "http://www.sougou.com"));
/**
*<a href="http://www.sougou.com">百度</a>
* <a href="http://www.sougou.com">谷歌</a>
*/
let str = `手机号1:17612345678,手机号2:13987654321`;
let reg = /(?<=\d{7})\d{4}/g;
console.log(str.replace(reg, "*".repeat(4)));
// 手机号1:1761234****,手机号2:1398765****
-
?!
后面不是什么
let str = `JonSnow1234Cercei`;
let reg = /[A-z]+(?!\d+)/g;
console.log(str.match(reg)); // ["JonSno", "Cercei"]
let reg1 = /[A-z]+(?!\d+)$/g;
console.log(str.match(reg1)); // ["Cercei"]
^(?!.*aa.*)
表示开始的后面不能包含aa
let reg = /^(?!.*aa.*).*/g;
let str = `bbccdd`;
console.log(reg.test(str)); // true
let str1 = `bbccdd`;
console.log(reg.test(str1)); // false
-
?<!
前面不是什么
let str = `JonSnow12Cercei`;
let reg = /(?<!\d)[A-z]+/g;
console.log(str.match(reg)); // ["JonSnow", "ercei"]
网友评论