Skip to content

Commit 5da0713

Browse files
committed
perf: speed up escapeHTML by ~3x
1 parent a846d19 commit 5da0713

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

frontend/src/ts/utils/misc.ts

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -164,18 +164,22 @@ export function escapeRegExp(str: string): string {
164164
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
165165
}
166166

167-
export function escapeHTML(str: string): string {
167+
export function escapeHTML<T extends string | null | undefined>(str: T): T {
168168
if (str === null || str === undefined) {
169169
return str;
170170
}
171-
str = str
172-
.replace(/&/g, "&amp;")
173-
.replace(/</g, "&lt;")
174-
.replace(/>/g, "&gt;")
175-
.replace(/"/g, "&quot;")
176-
.replace(/'/g, "&#039;");
177-
178-
return str;
171+
172+
const escapeMap: Record<string, string> = {
173+
"&": "&amp;",
174+
"<": "&lt;",
175+
">": "&gt;",
176+
'"': "&quot;",
177+
"'": "&#39;",
178+
"/": "&#x2F;",
179+
"`": "&#x60;",
180+
};
181+
182+
return str.replace(/[&<>"'/`]/g, (char) => escapeMap[char] as string) as T;
179183
}
180184

181185
export function isUsernameValid(name: string): boolean {

0 commit comments

Comments
 (0)