Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(labs/ssr): use RegExp.exec to escape HTML #4627

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
63 changes: 49 additions & 14 deletions packages/labs/ssr/src/lib/util/escape-html.ts
Expand Up @@ -4,22 +4,57 @@
* SPDX-License-Identifier: BSD-3-Clause
*/

const replacements = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
// Note &apos; was not defined in the HTML4 spec, and is not supported by very
// old browsers like IE8, so a codepoint entity is used instead.
"'": '&#39;',
};
const escapePattern = /[&<>"']/g;

/**
* Replaces characters which have special meaning in HTML (&<>"') with escaped
* HTML entities ("&amp;", "&lt;", etc.).
*/
export const escapeHtml = (str: string) =>
str.replace(
/[&<>"']/g,
(char) => replacements[char as keyof typeof replacements]
);
export const escapeHtml = (str: string) => {
let match = escapePattern.exec(str);

if (!match) {
return str;
}

let escapeStr;
let html = '';
let lastIndex = 0;

while (match) {
switch (str.charCodeAt(match.index)) {
// Character: "
case 34:
escapeStr = '&quot;';
break;
// Character: &
case 38:
escapeStr = '&amp;';
break;
// Character: '
// Note &apos; was not defined in the HTML4 spec, and is not supported by
// very old browsers like IE8, so a codepoint entity is used instead.
case 39:
escapeStr = '&#39;';
break;
// Character: <
case 60:
escapeStr = '&lt;';
break;
// Character: >
case 62:
escapeStr = '&gt;';
break;
}

html += str.substring(lastIndex, match.index) + escapeStr;
lastIndex = match.index + 1;
match = escapePattern.exec(str);
}

escapePattern.lastIndex = 0;

return lastIndex !== str.length - 1
? html + str.substring(lastIndex, str.length)
: html;
};