-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathjsonToRawHtmlScriptValue.mjs
More file actions
34 lines (30 loc) · 900 Bytes
/
jsonToRawHtmlScriptValue.mjs
File metadata and controls
34 lines (30 loc) · 900 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// @ts-check
// Inspiration:
// https://github.com/vercel/next.js/blob/81c3cd682b301d623df450c69ad2cf225b5aa570/packages/next/server/htmlescape.ts
// https://github.com/zertosh/htmlescape/blob/02dbcc367dd3069b73253ac08d87a40d37984239/htmlescape.js
/**
* JSON HTML escape map.
* @satisfies {{ [key: string]: string }}
*/
const jsonHtmlEscapes = {
"&": "\\u0026",
"<": "\\u003c",
">": "\\u003e",
"\u2028": "\\u2028",
"\u2029": "\\u2029",
};
/**
* HTML escapes a JSON string for use as a raw JavaScript value within a
* templated HTML script.
* @param {string} json JSON.
*/
export default function jsonToRawHtmlScriptValue(json) {
if (typeof json !== "string") {
throw new TypeError("Argument 1 `json` must be a string.");
}
return json.replace(
/[&<>\u2028\u2029]/gu,
(match) =>
jsonHtmlEscapes[/** @type {keyof typeof jsonHtmlEscapes} */ (match)],
);
}