Fastest way to detect external URLs

mate64 picture mate64 · Jun 4, 2011 · Viewed 23.3k times · Source

What's the fastest method to detect if foo='http://john.doe' is an external (in comparsion to window.location.href)?

Answer

Gumbo picture Gumbo · Jun 4, 2011

If you consider a URL being external if either the scheme, host or port is different, you could do something like this:

function isExternal(url) {
    var match = url.match(/^([^:\/?#]+:)?(?:\/\/([^\/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/);
    if (typeof match[1] === "string" && match[1].length > 0 && match[1].toLowerCase() !== location.protocol) return true;
    if (typeof match[2] === "string" && match[2].length > 0 && match[2].replace(new RegExp(":("+{"http:":80,"https:":443}[location.protocol]+")?$"), "") !== location.host) return true;
    return false;
}