RegExp.escape.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. describe("errors", () => {
  2. test("invalid string", () => {
  3. expect(() => {
  4. RegExp.escape(Symbol.hasInstance);
  5. }).toThrowWithMessage(TypeError, "Symbol(Symbol.hasInstance) is not a string");
  6. });
  7. });
  8. describe("normal behavior", () => {
  9. test("first character is alphanumeric", () => {
  10. const alphanumeric = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  11. for (const ch of alphanumeric) {
  12. const string = `${ch}${ch}${ch}`;
  13. const expected = `\\x${ch.codePointAt(0).toString(16)}${ch}${ch}`;
  14. expect(RegExp.escape(string)).toBe(expected);
  15. }
  16. });
  17. test("syntax characters", () => {
  18. const syntaxCharacters = "^$\\.*+?()[]{}|/";
  19. for (const ch of syntaxCharacters) {
  20. const string = `_${ch}_`;
  21. const expected = `_\\${ch}_`;
  22. expect(RegExp.escape(string)).toBe(expected);
  23. }
  24. });
  25. test("control characters", () => {
  26. expect(RegExp.escape("_\t_")).toBe("_\\t_");
  27. expect(RegExp.escape("_\n_")).toBe("_\\n_");
  28. expect(RegExp.escape("_\v_")).toBe("_\\v_");
  29. expect(RegExp.escape("_\f_")).toBe("_\\f_");
  30. expect(RegExp.escape("_\r_")).toBe("_\\r_");
  31. });
  32. test("punctuators", () => {
  33. const punctuators = ",-=<>#&!%:;@~'`\"";
  34. for (const ch of punctuators) {
  35. const string = `_${ch}_`;
  36. const expected = `_\\x${ch.codePointAt(0).toString(16)}_`;
  37. expect(RegExp.escape(string)).toBe(expected);
  38. }
  39. });
  40. test("non-ASCII whitespace", () => {
  41. const nbsp = "\u00A0";
  42. expect(RegExp.escape("\u00A0")).toBe("\\xa0");
  43. expect(RegExp.escape("\uFEFF")).toBe("\\ufeff");
  44. expect(RegExp.escape("\u2028")).toBe("\\u2028");
  45. expect(RegExp.escape("\u2029")).toBe("\\u2029");
  46. });
  47. test("Unicode surrogates", () => {
  48. for (let ch = 0xd800; ch <= 0xdfff; ++ch) {
  49. const string = String.fromCodePoint(ch);
  50. const expected = `\\u${ch.toString(16)}`;
  51. expect(RegExp.escape(string)).toBe(expected);
  52. }
  53. });
  54. });