Skip to content

Commit

Permalink
hoist dict
Browse files Browse the repository at this point in the history
  • Loading branch information
benmccann committed Feb 9, 2022
1 parent 2495005 commit 8d07e80
Showing 1 changed file with 11 additions and 17 deletions.
28 changes: 11 additions & 17 deletions packages/kit/src/utils/escape.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
/** @type {Record<string, string>} */
const escape_json_in_html_dict = {
'&': '\\u0026',
'>': '\\u003e',
'<': '\\u003c',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};

/** @type {Record<string, string>} */
const escape_json_value_in_html_dict = {
'"': '\\"',
'<': '\\u003C',
'>': '\\u003E',
'/': '\\u002F',
Expand All @@ -14,12 +24,6 @@ const escape_json_in_html_dict = {
'\u2029': '\\u2029'
};

/** @type {Record<string, string>} */
const escape_json_value_in_html_dict = {
'"': '\\"',
...escape_json_in_html_dict
};

/**
* Escape a stringified JSON object that's going to be embedded in a `<script>` tag
* @param {string} str
Expand All @@ -28,17 +32,7 @@ export function escape_json_in_html(str) {
// adapted from https://github.com/vercel/next.js/blob/694407450638b037673c6d714bfe4126aeded740/packages/next/server/htmlescape.ts
// based on https://github.com/zertosh/htmlescape
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
/**
* @type { Record<string, string> }
*/
const escape_lookup = {
'&': '\\u0026',
'>': '\\u003e',
'<': '\\u003c',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};
return str.replace(/[&><\u2028\u2029]/g, (match) => escape_lookup[match]);
return str.replace(/[&><\u2028\u2029]/g, (match) => escape_json_in_html_dict[match]);
}

/**
Expand Down

0 comments on commit 8d07e80

Please sign in to comment.