-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathencodeHtml.ts
More file actions
executable file
·28 lines (25 loc) · 787 Bytes
/
encodeHtml.ts
File metadata and controls
executable file
·28 lines (25 loc) · 787 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
import { requireNonEmptyString } from "../lang";
/**
* Encodes characters in a string (from `U+00A0` to `U+9999`) into their corresponding HTML entities.
*
* @param {string} value - The string to encode.
* @returns {string} The string with HTML-encoded characters.
* @throws {@link EmptyStringException}
* @see {@link decodeHtml}
* @since 1.0.0
* @version 1.1.0
*/
export function encodeHtml(value: string): string {
return requireNonEmptyString(value).replace(
/([\u00A0-\u9999<>&])(.|$)/g,
function (full, char, next) {
if (char !== "&" || next !== "#") {
if (/[\u00A0-\u9999<>&]/.test(next)) {
next = `&#${next.charCodeAt(0)};`;
}
return `&#${char.charCodeAt(0)};${next}`;
}
return full;
}
);
}