escapeJs
import { escapeJs } from "jsr:@ende/html/unstable-escape-js";function ยท experimental
function escapeJs(data: unknown, options: EscapeJsOptions = [UNSUPPORTED]): stringEscapes a JavaScript object or other data for safe interpolation inside a <script> tag.
The data must be JSON-serializable (plain object, array, string, number (excluding NaN/infinities), boolean, or null).
The output is fully JSON-compatible, with additional escaping of sequences that can be problematic within <script> tags.
data: unknownThe data to escape.
options: EscapeJsOptions = [UNSUPPORTED]Options for escaping.
Returns
The escaped string.
Example: Escaping a string
import { escapeJs } from "@ende/html/unstable-escape-js";
import { assertEquals } from "@ende/assert";
const input = "\u2028\u2029</script>";
assertEquals(escapeJs(input), '"\\u2028\\u2029\\u003c/script>"');
Example: Escaping an object
import { escapeJs } from "@ende/html/unstable-escape-js";
import { assertEquals } from "@ende/assert";
const input = {
"<SCRIPT>": "</script>",
"<!--": "\u2028\u2029<>",
};
assertEquals(
escapeJs(input),
'{"\\u003cSCRIPT>":"\\u003c/script>","\\u003c!--":"\\u2028\\u2029<>"}',
);
Example: Interpolating arbitrary data in a script tag
// might be nested arbitrarily deeply
declare const data: string | number | Record<string, string> | Record<string, Record<string, string>>;
const scriptHtml = `<script>window.handleData(${escapeJs(data)})</script>`;
Example: Interpolating into a JSON script (e.g. importmap)
const importMap = { imports: { zod: 'https://esm.sh/v131/[email protected]' } };
const importMapHtml = `<script type="importmap">${escapeJs(importMap)}</script>`;