检测外部 URL 的最快方法 [英] Fastest way to detect external URLs

查看:31
本文介绍了检测外部 URL 的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检测 foo='http://john.doe' 是否为外部 (与 window.location.href 相比)?

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

推荐答案

更新:我做了更多的研究,发现使用 new URL 已经足够快了,而且IMO 最直接的方式.

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.

需要注意的是,我尝试过的每种方法都需要不到 1 毫秒,即使在旧手机上也能运行.所以性能不应该是你的主要考虑因素,除非你在做一些大批量处理.如果性能是您的首要任务,请使用正则表达式版本.

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:

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);
}

正则表达式:

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);
  }
})();

以下是我用来测试性能的一些基本测试:https://is-external-url-test.glitch.me/

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

这篇关于检测外部 URL 的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆