我得到了一个像这样的URL:
http://google.de/test.php?a=b&c=d&e=f
我知道如何仅修改一个 GET 参数,就像这样:(
c
是 "h" 而不是 "d")http://google.de/test.php?a=b&c=h&e=f
并重定向到新的URL,所有其他GET参数应保持不变。
我该如何做到这一点?
我得到了一个像这样的URL:
http://google.de/test.php?a=b&c=d&e=f
c
是 "h" 而不是 "d")http://google.de/test.php?a=b&c=h&e=f
并重定向到新的URL,所有其他GET参数应保持不变。
我该如何做到这一点?
我同意其他答案中提到的最好使用库来完成此任务。
但是,如果你需要一个更简单快速的解决方法,这里提供了基于正则表达式的字符串替换方案。
var url = "http://my.com/page?x=y&z=1&w=34";
var regEx = /([?&]z)=([^#&]*)/g;
var newurl = url.replace(regEx, '$1=newValue');
这里我正在将查询字符串键“z”替换为“newValue”。
看看这个fiddle:http://jsfiddle.net/BuddhiP/PkNsx
如上所述,window.location.search
将返回包含?
的查询字符串。
然后,我会将它们转换为一个对象(可能使用类似http://github.com/medialize/URI.js的库),以便更轻松地处理参数,例如:var params = { key: value, key1: value1}
然后,您可以修改所需的值并将键值对转换回查询字符串。
完成后,您可以使用window.location
将用户移动到下一页。
location.href = location.href + '&c=h';
简单。
http://example.org/file?param1=value1#abc&c=h
是一个无效的URL。) - Zulakishttp://example.org/file.php&c=h
是一个无效的URL。 - Zulakisvar url = 'http://google.de/test.php?a=b&c=d&e=f';
var gets = url.split('.php?');
var ge = gets[1].split('&');
var change = ge[1].split('=');
var change[1] = 'h';
var newUrl = url[0] + '.php?' + ge[0] + '&' + change[0] + '=' + change[1] + '&' + ge[2];
var changed = "h"; // you can vary this GET parameter
var url = "http://google.de/test.php?a=b&e=f&c=" + changed; // append it to the end
window.location = newurl; // redirect the user to the url
由于您的参数可以在任何位置,所以这将很好地工作。
url="http://google.de/test.php?a=b&c=d&e=f";
url=url.replace(/&c=.*&/,"&c=h&")
设置或更新URL/查询字符串参数,并使用HTML history.replaceState()更新URL
你可以尝试类似这样的代码:
var updateQueryStringParam = function (key, value) {
var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
urlQueryString = document.location.search,
newParam = key + '=' + value,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (urlQueryString) {
keyRegex = new RegExp('([\?&])' + key + '[^&]*');
// If param exists already, update it
if (urlQueryString.match(keyRegex) !== null) {
params = urlQueryString.replace(keyRegex, "$1" + newParam);
} else { // Otherwise, add it to end of query string
params = urlQueryString + '&' + newParam;
}
}
window.history.replaceState({}, "", baseUrl + params);
};
location.href = location.origin+location.pathname+location.search;
将location.search替换为你的新参数,例如"?foo=bar&tic=tac"
/([?&]z)=([^#&]*)/g;
而不是/([?&]z)=([^&]*)/g;
,因为后者可能会覆盖片段。 - Zulakis