拆分 URL 以使用 Javascript 设置 cookie
Split URL to set cookie using Javascript
希望你能帮上忙。我想我快到了,但我的代码中有一个小错误。我正在尝试设置一个 cookie,它根据页面的一部分设置 cookie 值 url。
例如,我的 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 时。我猜我的代码是在最后一个之后获取内容/是否有一种方法可以指定在第二个之后获取内容/而不是?
下面的代码
<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:
使用 window.location.pathname
returns:
"/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=/;`
});
<script>$("#carbtn").bind("click", function() {
const strings = window.location.href.split("/").filter(str => !!str);
document.cookie=`model=${strings[strings.length - 1]};path=/;`
});</script>
此代码获取“/”拆分的最后一个元素,因此“/my/path/”获取“path/[HERE]”之后的空字符串,您可能需要深入研究可怕的 (或精彩)正则表达式的世界
const lastItemOnURL = window.location.pathname.match(/[^\/]+\/?$/);
if (lastItemOnURL[0]) { document.cookie = `model=${lastItemOnURL[0].replace('/', '')};path=/;` }
请注意,window.location.pathname 不会在 URL 中获取最终的 ?get=values,因此您可能也需要它
希望你能帮上忙。我想我快到了,但我的代码中有一个小错误。我正在尝试设置一个 cookie,它根据页面的一部分设置 cookie 值 url。
例如,我的 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 时。我猜我的代码是在最后一个之后获取内容/是否有一种方法可以指定在第二个之后获取内容/而不是?
下面的代码
<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:
使用 window.location.pathname
returns:
"/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=/;`
});
<script>$("#carbtn").bind("click", function() {
const strings = window.location.href.split("/").filter(str => !!str);
document.cookie=`model=${strings[strings.length - 1]};path=/;`
});</script>
此代码获取“/”拆分的最后一个元素,因此“/my/path/”获取“path/[HERE]”之后的空字符串,您可能需要深入研究可怕的 (或精彩)正则表达式的世界
const lastItemOnURL = window.location.pathname.match(/[^\/]+\/?$/);
if (lastItemOnURL[0]) { document.cookie = `model=${lastItemOnURL[0].replace('/', '')};path=/;` }
请注意,window.location.pathname 不会在 URL 中获取最终的 ?get=values,因此您可能也需要它