Skip to content

Instantly share code, notes, and snippets.

@HereOrCode
Created April 20, 2022 08:43
Show Gist options
  • Save HereOrCode/79c35d31def68f8d81e9c9b754e41956 to your computer and use it in GitHub Desktop.
Save HereOrCode/79c35d31def68f8d81e9c9b754e41956 to your computer and use it in GitHub Desktop.
零宽断言示例
// 正向零宽断言
// 肯定
const testStr1 = "iPhone3iPhone4iPhone5iPhoneNumber";
const reg1 = /iPhone(?=\d)/g;
const result1 = testStr1.replace(reg1, "MyPhone");
console.log(result1);
// MyPhone3MyPhone4MyPhone5iPhoneNumber
// 否定
const testStr2 = "iPhone3iPhone4iPhone5iPhoneNumber";
const reg2 = /iPhone(?!\d)/g;
const result2 = testStr2.replace(reg2, "MyPhone");
console.log(result2);
// iPhone3iPhone4iPhone5MyPhoneNumber
// 负向零宽断言
// 肯定
const testStr3 = "10px20px30pxmypx";
const reg3 = /(?<=\d+)px/g;
const result3 = testStr3.replace(reg3, "rem");
console.log(result3)
// 10rem20rem30remmypx
// 否定
const testStr4 = "10px20px30pxmypx";
const reg4 = /(?<!\d+)px/g;
const result4 = testStr4.replace(reg4, "rem");
console.log(result4)
// 10px20px30pxmyrem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment