我有这个URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
我需要的是能够改变'行' url参数值我指定的东西,让我们说10。如果“行”不存在,我需要将它添加到url的末尾,并添加我已经指定的值(10)。
我有这个URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
我需要的是能够改变'行' url参数值我指定的东西,让我们说10。如果“行”不存在,我需要将它添加到url的末尾,并添加我已经指定的值(10)。
当前回答
我也在找同样的东西,发现:https://github.com/medialize/URI.js,这是相当不错:)
- - -更新
我找到了一个更好的包:https://www.npmjs.org/package/qs,它还处理get参数中的数组。
其他回答
我是这么做的。使用我的editParams()函数,你可以添加,删除或更改任何参数,然后使用内置的replaceState()函数更新URL:
window.history.replaceState('object or string', 'Title', 'page.html' + editParams('sorting', ModifiedTimeAsc));
// background functions below:
// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
key = encodeURI(key);
var params = getSearchParameters();
if (Object.keys(params).length === 0) {
if (value !== false)
return '?' + key + '=' + encodeURI(value);
else
return '';
}
if (value !== false)
params[key] = encodeURI(value);
else
delete params[key];
if (Object.keys(params).length === 0)
return '';
return '?' + $.map(params, function (value, key) {
return key + '=' + value;
}).join('&');
}
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
let url= new url ("https://example.com/site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc") url.searchParams。设置(“行”,10) console.log (url.toString ())
我认为你需要查询插件。
例如:
window.location.search = jQuery.query.set("rows", 10);
不管行当前的状态如何,这都可以工作。
四年后,在我学到了很多东西之后,来回答我自己的问题。特别是你不应该对所有事情都使用jQuery。我已经创建了一个简单的模块,可以解析/stringify查询字符串。这使得修改查询字符串变得很容易。
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);
快速的纯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'。