main
Last change
on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago |
Initial commit
|
-
Property mode
set to
100644
|
File size:
1.2 KB
|
Line | |
---|
1 | import {
|
---|
2 | BLANK_URL,
|
---|
3 | ctrlCharactersRegex,
|
---|
4 | htmlCtrlEntityRegex,
|
---|
5 | htmlEntitiesRegex,
|
---|
6 | invalidProtocolRegex,
|
---|
7 | relativeFirstCharacters,
|
---|
8 | urlSchemeRegex,
|
---|
9 | } from "./constants";
|
---|
10 |
|
---|
11 | function isRelativeUrlWithoutProtocol(url: string): boolean {
|
---|
12 | return relativeFirstCharacters.indexOf(url[0]) > -1;
|
---|
13 | }
|
---|
14 |
|
---|
15 | // adapted from https://stackoverflow.com/a/29824550/2601552
|
---|
16 | function decodeHtmlCharacters(str: string) {
|
---|
17 | const removedNullByte = str.replace(ctrlCharactersRegex, "");
|
---|
18 | return removedNullByte.replace(htmlEntitiesRegex, (match, dec) => {
|
---|
19 | return String.fromCharCode(dec);
|
---|
20 | });
|
---|
21 | }
|
---|
22 |
|
---|
23 | export function sanitizeUrl(url?: string): string {
|
---|
24 | if (!url) {
|
---|
25 | return BLANK_URL;
|
---|
26 | }
|
---|
27 |
|
---|
28 | const sanitizedUrl = decodeHtmlCharacters(url)
|
---|
29 | .replace(htmlCtrlEntityRegex, "")
|
---|
30 | .replace(ctrlCharactersRegex, "")
|
---|
31 | .trim();
|
---|
32 |
|
---|
33 | if (!sanitizedUrl) {
|
---|
34 | return BLANK_URL;
|
---|
35 | }
|
---|
36 |
|
---|
37 | if (isRelativeUrlWithoutProtocol(sanitizedUrl)) {
|
---|
38 | return sanitizedUrl;
|
---|
39 | }
|
---|
40 |
|
---|
41 | const urlSchemeParseResults = sanitizedUrl.match(urlSchemeRegex);
|
---|
42 |
|
---|
43 | if (!urlSchemeParseResults) {
|
---|
44 | return sanitizedUrl;
|
---|
45 | }
|
---|
46 |
|
---|
47 | const urlScheme = urlSchemeParseResults[0];
|
---|
48 |
|
---|
49 | if (invalidProtocolRegex.test(urlScheme)) {
|
---|
50 | return BLANK_URL;
|
---|
51 | }
|
---|
52 |
|
---|
53 | return sanitizedUrl;
|
---|
54 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.