javascript - 拆分 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>
解决方案
如果您使用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=/;`
});
推荐阅读
- c# - 在 C# 中使用 LINQ to SQL 在 Cosmos DB 中查询动态键嵌套字典结构
- javascript - React:对象的默认属性
- css - 显示 json 本地
- linux - 我们可以将“cd ..”路径存储在 bash 文件的变量中吗?
- jasper-reports - 防止在 JasperReports 中对列标题进行分组
- html - 如何根据视口高度缩小图像?
- python - 如何将常量添加到 numpy 数组,但跳过 Python 中的第一行
- reactjs - React Formik:如何使用 formik 值的 useEffect?
- continuous-integration - 在具有多个微服务的 monorepo 中使用 bitbucket 管道进行选择性服务部署
- jenkins - 有什么方法可以检查我在 Jenkins 上运行的构建历史记录吗?