utility.js 2.03 KB
Newer Older
1 2
// checks whether or not the url is external to the local site.
// generously provided by StackOverflow: http://stackoverflow.com/questions/6238351/fastest-way-to-detect-external-urls
3
window.isExternal = function(url) {
4 5 6 7
    // parse the url into protocol, host, path, query, and fragment. More information can be found here: http://tools.ietf.org/html/rfc3986#appendix-B
    var match = url.match(/^([^:\/?#]+:)?(?:\/\/([^\/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/);
    // match[1] matches a protocol if one exists in the url
    // if the protocol in the url does not match the protocol in the window's location, this url is considered external
8
    if (typeof match[1] === 'string' &&
9 10
            match[1].length > 0 &&
            match[1].toLowerCase() !== location.protocol)
11 12 13
        return true;
    // match[2] matches the host if one exists in the url
    // if the host in the url does not match the host of the window location, this url is considered external
14
    if (typeof match[2] === 'string' &&
15
            match[2].length > 0 &&
16
            // this regex removes the port number if it patches the current location's protocol
17
            match[2].replace(new RegExp(':(' + {'http:': 80, 'https:': 443}[location.protocol] + ')?$'), '') !== location.host)
18 19
        return true;
    return false;
20
};
21 22 23 24

// Utility method for replacing a portion of a string.
window.rewriteStaticLinks = function(content, from, to) {
    if (from === null || to === null) {
25
        return content;
26
    }
27
    // replace only relative urls
28 29
    function replacer(match) {
        if (match === from) {
30 31 32 33 34 35 36 37
            return to;
        }
        else {
            return match;
        }
    }
    // change all relative urls only which may be embedded inside other tags in content.
    // handle http and https
38 39
    // escape all regex interpretable chars
    fromRe = from.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
40
    var regex = new RegExp('(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}([-a-zA-Z0-9@:%_\+.~#?&//=]*))?' + fromRe, 'g');
41
    return content.replace(regex, replacer);
42
};