mate64 mate64 - 2 months ago 6x
Javascript Question

Fastest way to detect external URLs

What's the fastest method to detect if

is an external (in comparsion to


I know the regex version has already been accepted but I would bet this is "faster" than doing that complex of a regex. String.replace is quite fast.

var isExternal = function(url) {
    var domain = function(url) {
        return url.replace('http://','').replace('https://','').split('/')[0];

    return domain(location.href) !== domain(url);


I decided to do a little more research on this and found a faster method that uses a Regex.

var isExternalRegexClosure = (function(){
    var domainRe = /https?:\/\/((?:[\w\d]+\.)+[\w\d]{2,})/i;

    return function(url) {
        function domain(url) {
          return domainRe.exec(url)[1];  

        return domain(location.href) !== domain(url);

In IE this is slightly faster than the String.replace method. However in Chrome and Firefox it is about twice as fast. Also, defining the Regex only once inside the closure instead of just inside the function normally is about 30% faster in Firefox.

Here is a jsperf examining four different ways of determining an external hostname.

It is important to note that every method I've tried takes less than 1ms to run even on an old phone. So performance probably shouldn't be your primary consideration unless you are doing some large batch processing.