如何保留 URL 主机/域的大小写(URL() 构造函数)

问题描述 投票:0回答:1

URL() 构造函数将主机名/域的大小写标准化为小写:

(new URL('https://WWW.EXAMPLE.COM/THIS/is/a/PATH')).href
// => 'https://www.example.com/THIS/is/a/PATH'

获取主机名和 href 字符串并保留主机名大小写的最简单方法是什么?有什么比手动解析域名,然后替换 URL.href 的结果更好的方法吗?

我想查询/操作 URL(例如删除不必要的查询参数),但保留域的大小写。虽然域名不区分大小写,但有时主机名中会包含大写字符以使其更具可读性(例如 expertsexchange.com)。

javascript url
1个回答
0
投票

这似乎是最简单/最不容易出错的方法(无需手动 URL 解析):

const url = 'https://www.EXAMPLE.com/THIS/is/a/PATH'
console.log(url)

const urlObject = new URL(url)

// 1. Create a case-insensitive regular expression based on URL.hostname.
const hostnameRE = new RegExp(urlObject.hostname, 'i')

// 2. Get the original mixed-cased domain using hostnameRE.
const hostnameOriginalCase = (url.match(hostnameRE))[0]

// Modify URL object:
urlObject.searchParams.set('new', 'param')

// 3. Replace the lowercase domain with the mixed case domain, gain using hostnameRE.
const urlWithOriginalCase = urlObject.href.replace(hostnameRE, hostnameOriginalCase)

// Results:
console.log(urlObject.href)
console.log(urlWithOriginalCase)

© www.soinside.com 2019 - 2024. All rights reserved.