Completed
Pull Request — master (#77)
by Sander
01:21
created

js/lib/parseUrl.js   A

Complexity

Total Complexity 24
Complexity/F 24

Size

Lines of Code 87
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 0
c 0
b 0
f 0
nc 1
dl 0
loc 87
rs 10
wmc 24
mnd 3
bc 24
fnc 1
bpm 24
cpm 24
noi 1
1
function processURL(URL, ignoreProtocol, ignoreSubdomain, ignorePath, ignorePort) {
2
    if (URL === null || URL === "") {
3
        return URL;
4
    }
5
6
    var URLobj = null;
0 ignored issues
show
Unused Code introduced by
The variable URLobj seems to be never used. Consider removing it.
Loading history...
7
    try {
8
        URLobj = new window.URL(URL);
9
    }
10
11
    catch (err) {
12
        if (ignoreProtocol) {
13
            try {
14
                URLobj = new window.URL("http://" + URL);
15
            }
16
            catch (err2) {
17
                return URL;
18
            }
19
        }
20
        else {
21
            return URL;
22
        }
23
    }
24
25
    var parser = document.createElement('a');
26
    parser.href = URL;
27
28
29
    var protocol = parser.protocol;
30
    var host = parser.hostname;
31
    var path = parser.pathname;
32
    var port = parser.port;
33
    if (host === null || host === "") {
34
        return URL;
35
    }
36
37
    var splittedURL = host.split(".");
38
    var isIP = false;
39
    if (splittedURL.length === 4) {
40
        isIP = true;
41
        for (var i = 0; i < splittedURL.length; i++) {
42
            if (isNaN(splittedURL[i]) || splittedURL[i] < 0 || splittedURL[i] > 255) {
43
                isIP = false;
44
                break;
45
            }
46
        }
47
    }
48
    var baseHost = null;
49
    if (isIP) {
50
        baseHost = host;
51
    }
52
    else {
53
        var tld = parse_host(host);
54
        if(tld) {
55
            baseHost = tld.domain;
56
        }
57
    }
58
    var returnURL = "";
59
    if (!ignoreProtocol) {
60
        returnURL += protocol + "//";
61
    }
62
63
    if (!ignoreSubdomain) {
64
        returnURL += host;
65
    }
66
    else {
67
        returnURL += baseHost;//return the hostname and the tld of the website if ignoreSubdomain is check
68
    }
69
70
    if (ignorePort) {
71
        if (port) {
72
            returnURL = returnURL.replace(':' + port, '');
73
        }
74
    } else {
75
        if (port) {
76
            returnURL += ':' + port;
77
        }
78
    }
79
80
    if (!ignorePath && path !== null && path) {
81
        returnURL += path;
82
    }
83
    if (returnURL.slice(-1) === "/") {
84
        returnURL = returnURL.slice(0, -1);
85
    }
86
    return returnURL;
87
}
88