简体   繁体   English

如何使用 hash 向 url 添加查询参数?

[英]How to add a query param to the url with hash?

I have an URL string: http:/some.other.com/#/app/ .我有一个 URL 字符串: http:/some.other.com/#/app/

I want to make it a string with a certain query param: http:/some.other.com/#/app/?my-param=whatever我想让它成为一个带有特定查询参数的字符串: http:/some.other.com/#/app/?my-param=whatever

I tried to do it like this:我试着这样做:

function addQueryParam(url, key, value) {
  const newUrl = new URL(url)
  newUrl.searchParams.set(key, value)
  return newUrl.toString()
}

addQueryParam('http:/some.other.com/#/app/', 'my-param', 'whatever')

I expected to have following URL:我预计会有以下 URL:

http:/some.other.com/#/app/?my-param=whatever

But the result is:但结果是:

http://some.other.com/?my-param=whatever#/app/

Maybe I missed something, but I guess a lot of apps such as angular, vue and I guess react use hash in the middle of the url string.也许我错过了一些东西,但我猜很多应用程序,例如 angular,vue 和我猜反应在 url 字符串中间使用 hash。 So how to add query params properly in that case?那么在这种情况下如何正确添加查询参数呢?

The comments are partially right, this information will not make it to the sever.评论部分正确,此信息不会发送到服务器。 However if you're just doing client side logic then nothing is stopping you.但是,如果您只是在做客户端逻辑,那么没有什么能阻止您。 Below is an example of how to achieve what you're looking for.下面是一个如何实现您正在寻找的示例。

 function addHashQueryParam(url, key, value) { const existing = (url.lastIndexOf('?') > url.lastIndexOf('#'))? url.substr(url.lastIndexOf('?') + 1): ''; const query = new URLSearchParams(existing); query.set(key, value) return `${url.replace(`?${existing}`, '')}?${query.toString()}`; } let url = 'http:/some.other.com/#/app/'; url = addHashQueryParam(url, 'my-param', 'whatever'); console.log(url) url = addHashQueryParam(url, 'my-second-param', 'whomever'); console.log(url)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM