在 JavaScript 中如何从 URL 解析 hostname

前端开发 Mar 30, 2022

在 JavaScript 中如何从 URL 解析 hostname,在前端开发领域,这是一个比较常见的诉求;当然,其解决方法很多,且也非常简单;只不过,在不同环境下,就须采取不同的方案;本文就与大家探讨下,在 JavaScript 中,从 URL 解析出 hostname 的各种手法。

在 JavaScript 中如何从 URL 解析 hostname

之前在开发倾城之链,就常遇见此类需求:需要根据所收录网址(url),根据其 hostname 获取到对应的应用截图;故而,下面就以 https://nicelinks.site/ 来做举例。

另外,需要说明的是,JavaScript 可以运行在多种场景,如浏览器、Node.js、小程序、快应用等;后面几种环境,没有 Window 对象,接口如 URL 也就不存在,如此一来,有些方法便不能使用。下面将从浏览器环境非浏览器环境,来探讨。

浏览器环境

下面谈到的方法,只能在浏览器环境使用。

借助 URL 对象

const urlObject = new URL("https://nicelinks.site/")
console.log(`hostname:`, urlObject.hostname)

备注:此特性在 Web Worker 中可用,在 Node.js 环境,无法使用。

通过创建 a 标签

const getLocation = function(href)  {
    const location = document.createElement("a")
    location.href = href;
    return location;
};
const location = getLocation("https://nicelinks.site/")
console.debug(`hostname:`, location.hostname)
const parser = document.createElement('a')
parser.href = 'https://nicelinks.site/'
console.debug(`hostname:`, location.hostname)

非浏览器环境

下面谈到的方法,因为是基于正则,在浏览器环境,或非浏览器环境,都能使用。

基于正则表达式

const urlPath = 'https://nicelinks.site/'
const matches = urlPath.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i)
const hostname = matches && matches[1]
console.debug(`hostname:`, hostname)

如果您想获得更多属性,如 href、protocol、host、port、hash 等,可以将封装一个函数,类似如下代码:

function getLocation(href) {
    var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
    return match && {
        href: href,
        protocol: match[1],
        host: match[2],
        hostname: match[3],
        port: match[4],
        pathname: match[5],
        search: match[6],
        hash: match[7]
    }
}
const locationObj = getLocation('https://nicelinks.site/')
console.debug(`hostname:`, locationObj.hostname)

倘若,您还有更简单(优雅)的方法,欢请留言分享^-^。

您可能感兴趣的文章

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.