正则新增特性

构造函数的变化 正则方法的扩展 u 修饰符 y 修饰符 s 修饰符

  1. {
  2. // es5
  3. let regex = new RegExp("xyz", "i");
  4. let regex2 = new RegExp(/xyz/i);
  5. console.log(regex.test("xyz123"), regex2.test("xyz123")); // true true
  6. // es6
  7. let regex3 = new RegExp(/xyz/gi, "i");
  8. console.log(regex3.flags); // i
  9. // ES6为正则表达式新增了flags属性,会返回正则表达式的修饰符。
  10. }
  11. {
  12. let s = "bbb_bb_b";
  13. let a1 = /b+/g;
  14. let a2 = /b+/y;
  15. console.log("one", a1.exec(s), a2.exec(s));
  16. // one ["bbb", index: 0, input: "bbb_bb_b", groups: undefined] ["bbb", index: 0, input: "bbb_bb_b", groups: undefined]
  17. console.log("two", a1.exec(s), a2.exec(s));
  18. // two ["bb", index: 4, input: "bbb_bb_b", groups: undefined] null
  19. console.log(a1.sticky, a2.sticky); // false true
  20. }
  21. {
  22. console.log("u-1", /^\uD83D/.test("\uD83D\uDC2A")); // u-1 true
  23. console.log("u-2", /^\uD83D/u.test("\uD83D\uDC2A")); // u-2 false
  24. console.log(/\u{61}/.test("a")); // false
  25. console.log(/\u{61}/u.test("a")); // true
  26. console.log(`\u{20BB7}`); // 𠮷
  27. let s = "𠮷";
  28. console.log("u-1", /^.$/.test(s)); // u-1 false
  29. console.log("u-2", /^.$/u.test(s)); // u-2 true
  30. console.log("test-1", /𠮷{2}/.test("𠮷𠮷")); // test-1 false
  31. console.log("test-2", /𠮷{2}/u.test("𠮷𠮷")); // test-2 true
  32. }