Skip to content

Commit 03959c3

Browse files
committed
Escape in regexp
1 parent 8b6f1f1 commit 03959c3

File tree

3 files changed

+18
-4
lines changed

3 files changed

+18
-4
lines changed

src/index.spec.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -221,9 +221,20 @@ describe("javascript-stringify", () => {
221221
});
222222

223223
describe("RegExp", () => {
224-
it("should stringify as shorthand", test(/[abc]/gi, "/[abc]/gi"));
224+
it(
225+
"should stringify as shorthand",
226+
test(/[abc]/gi, "new RegExp('[abc]', 'gi')"),
227+
);
225228

226-
it("should escape slashes", test(new RegExp("a/b"), "/a\\/b/"));
229+
it(
230+
"should escape slashes",
231+
test(new RegExp("a/b"), "new RegExp('a\\\\/b')"),
232+
);
233+
234+
it(
235+
"should escape html characters",
236+
test(new RegExp("<!--"), "new RegExp('\\u003c!--')"),
237+
);
227238
});
228239

229240
describe("Number", () => {

src/object.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,10 @@ const OBJECT_TYPES: Record<string, ToString> = {
9292
"[object Map]": (map: Map<any, any>, space: string, next: Next) => {
9393
return `new Map(${next(Array.from(map))})`;
9494
},
95-
"[object RegExp]": String,
95+
"[object RegExp]": (value: RegExp, space: string, next: Next) => {
96+
if (!value.flags) return `new RegExp(${next(value.source)})`;
97+
return `new RegExp(${next(value.source)}, ${next(value.flags)})`;
98+
},
9699
"[object global]": globalToString,
97100
"[object Window]": globalToString,
98101
};

src/stringify.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ const PRIMITIVE_TYPES: Record<string, ToString> = {
1616
if (key !== undefined) return `Symbol.for(${next(key)})`;
1717

1818
// ES2018 `Symbol.description`.
19-
return `Symbol(${next((value as any).description)})`;
19+
return `Symbol(${next(value.description)})`;
2020
},
2121
bigint: (value: bigint, space: string, next: Next) => {
2222
return `BigInt(${next(String(value))})`;

0 commit comments

Comments
 (0)