我有这个 URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
我需要做的是能够更改“rows”URL参数的值为我指定的值,比如说10。如果“rows”不存在,我需要将其添加到URL末尾,并添加我已经指定的值(10)。
我有这个 URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
我需要做的是能够更改“rows”URL参数的值为我指定的值,比如说10。如果“rows”不存在,我需要将其添加到URL末尾,并添加我已经指定的值(10)。
我已经扩展了Sujoy的代码以创建一个函数。
/**
* https://dev59.com/enNA5IYBdhLWcg3wGJ0V#10997390
*/
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
函数调用:
var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');
window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));
更新的版本还可以处理URL上的锚点。
function updateURLParameter(url, param, paramVal)
{
var TheAnchor = null;
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL)
{
var tmpAnchor = additionalURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheAnchor)
additionalURL = TheParams;
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++)
{
if(tempArray[i].split('=')[0] != param)
{
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
else
{
var tmpAnchor = baseURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheParams)
baseURL = TheParams;
}
if(TheAnchor)
paramVal += "#" + TheAnchor;
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
http://www.domain.com/index.php?action=my_action&view-all=Yes
,我需要更改“view-all”的值。我的SO问题已关闭:http://stackoverflow.com/questions/13025880/js-append-variable-to-url-without-repeating - DravenparamVal === null
时删除参数。
为此,我已将最后2行替换为以下内容:if ( paramVal !== null ) newAdditionalURL += temp + '' + param + '=' + paramVal; return baseURL + '?' + newAdditionalURL;
- caiosm1005""
连接到字符串上:var rows_txt = temp + "" + param + "=" + paramVal;
- HoldOffHungerwindow.location.pathname
即可。 - Matthew Flaschen用纯js快速解决方案,无需插件:
function replaceQueryParam(param, newval, search) {
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : '');
}
window.location = '/mypage' + replaceQueryParam('rows', 55, window.location.search)
var str = window.location.search
str = replaceQueryParam('rows', 55, str)
str = replaceQueryParam('cols', 'no', str)
window.location = window.location.pathname + str
编辑,感谢Luke:要完全删除参数,请将值传递为false
或null
:replaceQueryParam('rows', false, params)
。由于0
也是假的,请指定'0'
。
四年后,经过了很多学习,我自己回答了这个问题。特别是要注意不要把jQuery用于所有事情上。我创建了一个简单的模块,可以解析/字符串化查询字符串。这使得修改查询字符串变得容易。
你可以按照以下方式使用query-string:
// parse the query string into an object
var q = queryString.parse(location.search);
// set the `row` property
q.rows = 10;
// convert the object to a query string
// and overwrite the existing query string
location.search = queryString.stringify(q);
const paramsString = "site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc"
const searchParams = new URLSearchParams(paramsString);
searchParams.set('rows', 10);
console.log(searchParams.toString()); // return modified string.
site.fwx%3Fposition=1&archiveid=5000&columns=5&rows=10&sorting=ModifiedTimeAsc
,这很令人困惑,因为如果你手动构建它,它不会是这样的... - Ben Wheelernew URLSearchParams("site.fwx?position=1&...
应该改为 new URLSearchParams("position=1&...
(它只接受搜索字符串,而不是路径)。我已经编辑过来修复了,但是编辑被拒绝了?此外,@the-godfather提供的 const searchParams = new URLSearchParams(location.search); searchParams.set('rows', 10); location.search = searchParams;
是你想要在这个答案中添加的额外信息。 - bazzarghsearchParams.get('param')
获取参数。适用于 Node。 - The OninBen Alman有一个不错的jquery querystring/url插件在这里,可以轻松地操纵查询字符串。
按照要求 -
进入他的测试页面在这里
在Firebug控制台中输入以下内容
jQuery.param.querystring(window.location.href, 'a=3&newValue=100');
它将返回以下修改后的URL字符串
http://benalman.com/code/test/js-jquery-url-querystring.html?a=3&b=Y&c=Z&newValue=100#n=1&o=2&p=3
请注意查询字符串名称为a的值已从X更改为3,并添加了新值。
您随后可以使用新的url字符串,例如使用document.location = newUrl或更改锚链接等等
jQuery.param.querystring
。我猜他们已经重构了这个库。 - Will Wu这是现代更改URL参数的方法:
function setGetParam(key,value) {
if (history.pushState) {
var params = new URLSearchParams(window.location.search);
params.set(key, value);
var newUrl = window.location.origin
+ window.location.pathname
+ '?' + params.toString();
window.history.pushState({path:newUrl},'',newUrl);
}
}
document.title
作为历史记录标题。 - Amir2mi你也可以通过普通的JS来完成它
var url = document.URL
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var aditionalURL = tempArray[1];
var temp = "";
if(aditionalURL)
{
var tempArray = aditionalURL.split("&");
for ( var i in tempArray ){
if(tempArray[i].indexOf("rows") == -1){
newAdditionalURL += temp+tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp+"rows=10";
var finalURL = baseURL+"?"+newAdditionalURL+rows_txt;
var rows = 5; // value that you want to set
var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
url.search = url.searchParams;
url = url.toString();
// if you want to append into URL without reloading the page
history.pushState({}, null, url);
// want to reload the window with a new param
window.location = url;
2020年解决方案:如果将null
或undefined
传递到该值,则设置变量或删除它。
var setSearchParam = function(key, value) {
if (!window.history.pushState) {
return;
}
if (!key) {
return;
}
var url = new URL(window.location.href);
var params = new window.URLSearchParams(window.location.search);
if (value === undefined || value === null) {
params.delete(key);
} else {
params.set(key, value);
}
url.search = params;
url = url.toString();
window.history.replaceState({url: url}, null, url);
}
URLSearchParams
在所有主要浏览器的最新版本(2020年)中均无法使用。 - Oliver SchimmerpushState
?是为了检查它是否受支持吗? - M3RS
const myUrl = new URL("http://www.example.com?columns=5&rows=20");
myUrl.searchParams.set('rows', 10);
myUrl.href
将包含更新后的URL - sprutexhttp://www.example.com?columns=5&rows=20
替换为window.location.href
以使代码更具动态性。 - Waleed Khaled