首页 > 解决方案 > 拆分 URL 以使用 Javascript 设置 cookie

问题描述

希望你能提供帮助。我想我快到了,但我的代码有一个小错误。我正在尝试设置一个 cookie,它根据页面 url 的一部分设置 cookie 值。

例如,我的 cookie 名称是“model”,我的 cookie 值是根据 url 填充的

https://www.website.co.uk/cars/100sr/

在上面的示例中,cookie 值应设置为 100sr

但是,我刚刚注意到一个错误,如果客户使用 url 上的查询字符串访问我的网站,它将 cookie 值设置为查询字符串内容而不是 100sr

例如

https://www.website.co.uk/cars/100sr/?testing

上面使用我当前代码的 url 会将 cookie 设置为 ?testing 当我希望它仍然设置为 100sr 时。我猜我的代码是在 LAST / 之后获取内容,是否有办法指定在第二个 / 之后获取内容?

下面的代码

<script>$("#carbtn").bind("click", function() {
  const strings = window.location.href.split("/").filter(str => !!str);
  document.cookie=`model=${strings[strings.length - 1]};path=/;`
});</script>

标签: javascriptcookies

解决方案


如果您使用pathname代替href,您将能够检索没有查询字符串的 URL 部分。例如,在 URL 上:

拆分 URL 以使用 Javascript 设置 cookie

使用window.location.pathname回报:

"/questions/67402851/split-url-to-set-cookie-using-javascript"

这样做:

$("#carbtn").bind("click", function() {
  const strings = window.location.pathname.split("/").filter(str => !!str);
  document.cookie = `model=${strings[strings.length - 1]};path=/;`
});

推荐阅读