我有这个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)。
当前回答
我知道这是一个老问题。我增强了上面的功能,以添加或更新查询参数。仍然是一个纯JS解决方案。
function addOrUpdateQueryParam(param, newval, search) {
var questionIndex = search.indexOf('?');
if (questionIndex < 0) {
search = search + '?';
search = search + param + '=' + newval;
return search;
}
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
var indexOfEquals = query.indexOf('=');
return (indexOfEquals >= 0 ? query + '&' : query + '') + (newval ? param + '=' + newval : '');
}
其他回答
使用URLSearchParams检查,获取并设置参数值为URL
下面是获取当前URL并设置新参数并根据需要更新URL或重新加载页面的示例
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;
我扩展了Sujoy的代码来组成一个函数。
/**
* http://stackoverflow.com/a/10997390/11236
*/
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;
}
快速的纯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'。
一个可行的替代字符串操作的方法是建立一个html表单,只修改rows元素的值吗?
html就像是
<form id='myForm' target='site.fwx'>
<input type='hidden' name='position' value='1'/>
<input type='hidden' name='archiveid' value='5000'/>
<input type='hidden' name='columns' value='5'/>
<input type='hidden' name='rows' value='20'/>
<input type='hidden' name='sorting' value='ModifiedTimeAsc'/>
</form>
使用下面的JavaScript提交表单
var myForm = document.getElementById('myForm');
myForm.rows.value = yourNewValue;
myForm.submit();
可能不适合所有情况,但可能比解析URL字符串更好。
// usage: clear ; cd src/js/node/js-unit-tests/01-set-url-param ; npm test ; cd -
// prereqs: , nodejs , mocha
// URI = scheme:[//authority]path[?paramName1=paramValue1¶mName2=paramValue2][#fragment]
// call by: uri = uri.setUriParam("as","md")
String.prototype.setUriParam = function (paramName, paramValue) {
var uri = this
var fragment = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
uri = ( uri.indexOf('#') === -1 ) ? uri : uri.split('#')[0]
if ( uri.indexOf("?") === -1 ) { uri = uri + '?&' }
uri = uri.replace ( '?' + paramName , '?&' + paramName)
var toRepl = (paramValue != null) ? ('$1' + paramValue) : ''
var toSrch = new RegExp('([&]' + paramName + '=)(([^&#]*)?)')
uri = uri.replace(toSrch,toRepl)
if (uri.indexOf(paramName + '=') === -1 && toRepl != '' ) {
var ampersandMayBe = uri.endsWith('&') ? '' : '&'
uri = uri + ampersandMayBe + paramName + "=" + String(paramValue)
}
uri = ( fragment.length == 0 ) ? uri : (uri+"#"+fragment) //may-be re-add the fragment
return uri
}
var assert = require('assert');
describe('replacing url param value', function () {
// scheme://authority/path[?p1=v1&p2=v2#fragment
// a clean url
it('http://org.com/path -> http://org.com/path?&prm=tgt_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ? with num value
it('http://org.com/path?prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=57'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ? but string value
it('http://org.com/path?prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=boo-bar'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=boo-bar-baz'
var uriActual = uri.setUriParam("bid","boo-bar-baz")
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ?& but string value
it('http://org.com/path?&prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ? with other param
it('http://org.com/path?prm=src_v&other_p=other_v -> http://org.com/path?&prm=tgt_v&other_p=other_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p=other_v'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ?& with other param
it('http://org.com/path?&prm=src_v&other_p=other_v -> http://org.com/path?&prm=tgt_v&other_p=other_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p&other_v'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p&other_v'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ? with other param with fragment
it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p=other_v#f'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ?& with other param with fragment
it('http://org.com/path?&prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p&other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p&other_v#f'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// remove the param-name , param-value pair
it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
var uriActual = uri.setUriParam("bid",null)
assert.equal(uriActual, uriExpected);
});
// remove the param-name , param-value pair
it('http://org.com/path?&prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p=other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
var uriActual = uri.setUriParam("bid",null)
assert.equal(uriActual, uriExpected);
});
// add a new param name , param value pair
it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v&bid=foo-bar#f'
var uriActual = uri.setUriParam("bid","foo-bar")
assert.equal(uriActual, uriExpected);
});
});