|
1 | 1 | import * as t from "tap"; |
2 | 2 | import { escapeStringRegexp } from "./escapeStringRegexp"; |
3 | 3 |
|
4 | | -t.test("main", async (t) => { |
| 4 | +const isUsingBuiltIn = typeof (globalThis as any).RegExp?.escape === "function"; |
| 5 | + |
| 6 | +if (!isUsingBuiltIn) { |
| 7 | + t.test("main", async (t) => { |
| 8 | + t.same( |
| 9 | + escapeStringRegexp("\\ ^ $ * + ? . ( ) | { } [ ]"), |
| 10 | + "\\\\ \\^ \\$ \\* \\+ \\? \\. \\( \\) \\| \\{ \\} \\[ \\]" |
| 11 | + ); |
| 12 | + t.same(escapeStringRegexp("hello world"), "hello world"); |
| 13 | + }); |
| 14 | + |
| 15 | + t.test("escapes `-` in a way compatible with PCRE", async (t) => { |
| 16 | + t.same(escapeStringRegexp("foo - bar"), "foo \\x2d bar"); |
| 17 | + }); |
| 18 | + |
| 19 | + t.test("escapes `-` in a way compatible with the Unicode flag", async (t) => { |
| 20 | + t.ok(new RegExp(escapeStringRegexp("-"), "u").test("-")); |
| 21 | + }); |
| 22 | +} else { |
5 | 23 | t.same( |
6 | 24 | escapeStringRegexp("\\ ^ $ * + ? . ( ) | { } [ ]"), |
7 | | - "\\\\ \\^ \\$ \\* \\+ \\? \\. \\( \\) \\| \\{ \\} \\[ \\]" |
| 25 | + "\\\\\\x20\\^\\x20\\$\\x20\\*\\x20\\+\\x20\\?\\x20\\.\\x20\\(\\x20\\)\\x20\\|\\x20\\{\\x20\\}\\x20\\[\\x20\\]" |
8 | 26 | ); |
9 | | -}); |
10 | 27 |
|
11 | | -t.test("escapes `-` in a way compatible with PCRE", async (t) => { |
12 | | - t.same(escapeStringRegexp("foo - bar"), "foo \\x2d bar"); |
13 | | -}); |
| 28 | + t.test("escapes `-` in a way compatible with PCRE", async (t) => { |
| 29 | + t.same(escapeStringRegexp("foo - bar"), "\\x66oo\\x20\\x2d\\x20bar"); |
| 30 | + }); |
14 | 31 |
|
15 | | -t.test("escapes `-` in a way compatible with the Unicode flag", async (t) => { |
16 | | - t.ok(new RegExp(escapeStringRegexp("-"), "u").test("-")); |
| 32 | + t.test("escapes `-` in a way compatible with the Unicode flag", async (t) => { |
| 33 | + t.ok(new RegExp(escapeStringRegexp("-"), "u").test("-")); |
| 34 | + }); |
| 35 | +} |
| 36 | + |
| 37 | +t.test("escaped regex matches correctly", async (t) => { |
| 38 | + t.ok(new RegExp(escapeStringRegexp("hello world")).test("hello world")); |
| 39 | + t.ok( |
| 40 | + new RegExp(escapeStringRegexp("hello world \\d")).test("hello world \\d") |
| 41 | + ); |
| 42 | + t.ok(new RegExp(escapeStringRegexp("hello\\sworld")).test("hello\\sworld")); |
| 43 | + |
| 44 | + t.notOk( |
| 45 | + new RegExp(escapeStringRegexp("hello world \\d")).test("hello world 1") |
| 46 | + ); |
| 47 | + t.notOk(new RegExp(escapeStringRegexp("hello\\sworld")).test("hello sworld")); |
17 | 48 | }); |
0 commit comments