Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  47] [ 1]  / answers: 1 / hits: 33245  / 13 Years ago, sat, june 4, 2011, 12:00:00

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


More From » url

 Answers
10

Update: I did some more research and found that using new URL is easily fast enough, and IMO the most straight-forward way of doing this.


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


These are the three methods I tried:


new URL:


const isExternalURL = (url) => new URL(url).origin !== location.origin;

String.replace:


function isExternalReplace(url) {
const domain = (url) => url.replace('http://','').replace('https://','').split('/')[0];
return domain(location.href) !== domain(url);
}

Regex:


const isExternalRegex = (function(){
const domainRe = /https?://((?:[wd-]+.)+[wd]{2,})/i;

return (url) => {
const domain = (url) => domainRe.exec(url)[1];
return domain(location.href) !== domain(url);
}
})();

Here are some basic tests I used to test performance: https://is-external-url-test.glitch.me/


[#91864] Thursday, June 2, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxinec

Total Points: 117
Total Questions: 116
Total Answers: 116

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
maxinec questions
;