gpt4 book ai didi

javascript - 如何保存部分网址中的字符串?

转载 作者:行者123 更新时间:2023-11-28 17:29:51 24 4
gpt4 key购买 nike

给定以下 URL:

https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States

如何保存三个变量:

var date1: "2015";
var date2: "2017";
var loc = "United States";

注意:我们在网址2015+2017中有两个带有+符号的日期,我们需要将它们分开。网址 United-States 中有一个破折号,我们需要它作为 United States

这就是我正在尝试的:

function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var dates = getUrlVars()["usp-custom-14"];
var loc = getUrlVars()["usp-custom-8"];
var dateSplit = dates.split("+");

此外,由于其他原因,我需要在页面加载后再次更新 URL,我这样做了:

history.replaceState('data to be passed', 'Title of the page', '<?php echo getAddress(); ?>/?usp-custom-14='+dateSplit+'&usp-custom-8='+loc);

但是网址重复

https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States/?usp-custom-14=2015,2017&usp-custom-8=United-States

最佳答案

您可以在 ? 上拆分 url,并使用 pop() 返回结果数组的最后一个成员,这将是整个查询字符串。

从那里,您可以通过首先在 & 上拆分它,然后在 = 上拆分它来将其拆分为键值对。

我已将其放入一个函数中,以便您在需要时只需执行 getParam("my-url-parameter") 即可。使用它,然后处理特定参数上的 +-,您应该能够轻松获得您想要的内容。

它还应该可以在需要的地方重复使用。

function getParam(key) {
//var url = window.location.href; (Doesn't work on StackOverflow, but would be used in your real environment)
var url = "https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States";
var querystring = url.split("?").pop();
var params = {};
querystring.split("&").forEach((i) => params[i.split("=")[0]] = i.split("=")[1]); //Create key-value pairs
return params[key] || null;
}

var uspCustom14 = getParam("usp-custom-14").split("+");
var date1 = uspCustom14[0];
var date2 = uspCustom14[1];
var country = getParam("usp-custom-8").replace(/\-/g, ' ');

console.log(`Date 1: ${date1},`, `Date 2: ${date2},`, `Country: ${country}`);

对于第二个问题,您可以删除查询字符串并使用正确的值重新添加它:

var urlDates = getParam("usp-custom-14").replace('+',',');
var urlCountry = getParam("usp-custom-8");
history.replaceState('data to be passed', 'Title of the page', `${window.location.href.split("?")[0]}?usp-custom-14=${urlDates}&usp-custom-8=${urlCountry}`);

关于javascript - 如何保存部分网址中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50711554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com