在一个使用AJAX调用的web应用程序中,我需要提交一个请求,但在URL的末尾添加一个参数,例如:
原始URL:
http://server/myapp.php?id=10
导致的网址:
http://server/myapp.php?id=10&enabled=true
寻找一个JavaScript函数,该函数解析URL并查看每个参数,然后添加新参数或更新已经存在的值。
在一个使用AJAX调用的web应用程序中,我需要提交一个请求,但在URL的末尾添加一个参数,例如:
原始URL:
http://server/myapp.php?id=10
导致的网址:
http://server/myapp.php?id=10&enabled=true
寻找一个JavaScript函数,该函数解析URL并查看每个参数,然后添加新参数或更新已经存在的值。
你需要适应的基本实现是这样的:
function insertParam(key, value) {
key = encodeURIComponent(key);
value = encodeURIComponent(value);
// kvp looks like ['key1=value1', 'key2=value2', ...]
var kvp = document.location.search.substr(1).split('&');
let i=0;
for(; i<kvp.length; i++){
if (kvp[i].startsWith(key + '=')) {
let pair = kvp[i].split('=');
pair[1] = value;
kvp[i] = pair.join('=');
break;
}
}
if(i >= kvp.length){
kvp[kvp.length] = [key,value].join('=');
}
// can return this or...
let params = kvp.join('&');
// reload page with new params
document.location.search = params;
}
这大约是正则表达式或基于搜索的解决方案的两倍,但这完全取决于查询字符串的长度和任何匹配的索引
为了完成起见,我以慢速regex方法为基准(大约慢了150%)
function insertParam2(key,value)
{
key = encodeURIComponent(key); value = encodeURIComponent(value);
var s = document.location.search;
var kvp = key+"="+value;
var r = new RegExp("(&|\\?)"+key+"=[^\&]*");
s = s.replace(r,"$1"+kvp);
if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};
//again, do what you will here
document.location.search = s;
}
这是我自己的尝试,但我将使用annakata的答案,因为它看起来更清晰:
function AddUrlParameter(sourceUrl, parameterName, parameterValue, replaceDuplicates)
{
if ((sourceUrl == null) || (sourceUrl.length == 0)) sourceUrl = document.location.href;
var urlParts = sourceUrl.split("?");
var newQueryString = "";
if (urlParts.length > 1)
{
var parameters = urlParts[1].split("&");
for (var i=0; (i < parameters.length); i++)
{
var parameterParts = parameters[i].split("=");
if (!(replaceDuplicates && parameterParts[0] == parameterName))
{
if (newQueryString == "")
newQueryString = "?";
else
newQueryString += "&";
newQueryString += parameterParts[0] + "=" + parameterParts[1];
}
}
}
if (newQueryString == "")
newQueryString = "?";
else
newQueryString += "&";
newQueryString += parameterName + "=" + parameterValue;
return urlParts[0] + newQueryString;
}
另外,我从stackoverflow上的另一篇文章中找到了这个jQuery插件,如果你需要更多的灵活性,你可以使用它: http://plugins.jquery.com/project/query-object
我认为代码应该是(还没有测试):
return $.query.parse(sourceUrl).set(parameterName, parameterValue).toString();
我有一个'类',这是:
function QS(){
this.qs = {};
var s = location.search.replace( /^\?|#.*$/g, '' );
if( s ) {
var qsParts = s.split('&');
var i, nv;
for (i = 0; i < qsParts.length; i++) {
nv = qsParts[i].split('=');
this.qs[nv[0]] = nv[1];
}
}
}
QS.prototype.add = function( name, value ) {
if( arguments.length == 1 && arguments[0].constructor == Object ) {
this.addMany( arguments[0] );
return;
}
this.qs[name] = value;
}
QS.prototype.addMany = function( newValues ) {
for( nv in newValues ) {
this.qs[nv] = newValues[nv];
}
}
QS.prototype.remove = function( name ) {
if( arguments.length == 1 && arguments[0].constructor == Array ) {
this.removeMany( arguments[0] );
return;
}
delete this.qs[name];
}
QS.prototype.removeMany = function( deleteNames ) {
var i;
for( i = 0; i < deleteNames.length; i++ ) {
delete this.qs[deleteNames[i]];
}
}
QS.prototype.getQueryString = function() {
var nv, q = [];
for( nv in this.qs ) {
q[q.length] = nv+'='+this.qs[nv];
}
return q.join( '&' );
}
QS.prototype.toString = QS.prototype.getQueryString;
//examples
//instantiation
var qs = new QS;
alert( qs );
//add a sinle name/value
qs.add( 'new', 'true' );
alert( qs );
//add multiple key/values
qs.add( { x: 'X', y: 'Y' } );
alert( qs );
//remove single key
qs.remove( 'new' )
alert( qs );
//remove multiple keys
qs.remove( ['x', 'bogus'] )
alert( qs );
我已经重写了toString方法,所以不需要调用QS::getQueryString,你可以使用QS::toString,或者像我在示例中所做的那样,仅仅依赖于对象被强制转换为字符串。
好的,在这里我比较两个函数,一个由我自己(regExp)和另一个由(annakata)。
将数组:
function insertParam(key, value)
{
key = escape(key); value = escape(value);
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
return "&"+kvp.join('&');
}
正则表达式的方法:
function addParameter(param, value)
{
var regexp = new RegExp("(\\?|\\&)" + param + "\\=([^\\&]*)(\\&|$)");
if (regexp.test(document.location.search))
return (document.location.search.toString().replace(regexp, function(a, b, c, d)
{
return (b + param + "=" + value + d);
}));
else
return document.location.search+ param + "=" + value;
}
测试用例:
time1=(new Date).getTime();
for (var i=0;i<10000;i++)
{
addParameter("test","test");
}
time2=(new Date).getTime();
for (var i=0;i<10000;i++)
{
insertParam("test","test");
}
time3=(new Date).getTime();
console.log((time2-time1)+" "+(time3-time2));
似乎即使使用最简单的解决方案(当regexp只使用test而不输入.replace函数时),它仍然比分裂要慢…好。Regexp有点慢,但是…喔…
感谢大家的贡献。我使用annakata代码并修改为也包括url中根本没有查询字符串的情况。 希望这能有所帮助。
function insertParam(key, value) {
key = escape(key); value = escape(value);
var kvp = document.location.search.substr(1).split('&');
if (kvp == '') {
document.location.search = '?' + key + '=' + value;
}
else {
var i = kvp.length; var x; while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
}
}
这是一个非常简化的版本,为了可读性和更少的代码行而不是微观优化的性能(我们说的是几毫秒的差异,实际上……由于它的性质(操作当前文档的位置),这将很可能在一个页面上运行一次)。
/**
* Add a URL parameter (or changing it if it already exists)
* @param {search} string this is typically document.location.search
* @param {key} string the key to set
* @param {val} string value
*/
var addUrlParam = function(search, key, val){
var newParam = key + '=' + val,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (search) {
// Try to replace an existance instance
params = search.replace(new RegExp('([?&])' + key + '[^&]*'), '$1' + newParam);
// If nothing was replaced, then add the new param to the end
if (params === search) {
params += '&' + newParam;
}
}
return params;
};
然后你可以这样使用:
document.location.pathname + addUrlParam(document.location.search, 'foo', 'bar');
这是一个非常简单的解决方案。它不控制参数的存在,也不改变现有的值。它将参数添加到end,因此可以在后端代码中获得最新值。
function addParameterToURL(param){
_url = location.href;
_url += (_url.split('?')[1] ? '&':'?') + param;
return _url;
}
我喜欢穆罕穆德·法提赫·耶尔达兹的回答,即使他没有回答整个问题。
在他回答的同一行中,我使用了这样的代码:
“它不控制参数的存在,也不改变现有的值。它把你的参数加到最后"
/** add a parameter at the end of the URL. Manage '?'/'&', but not the existing parameters.
* does escape the value (but not the key)
*/
function addParameterToURL(_url,_key,_value){
var param = _key+'='+escape(_value);
var sep = '&';
if (_url.indexOf('?') < 0) {
sep = '?';
} else {
var lastChar=_url.slice(-1);
if (lastChar == '&') sep='';
if (lastChar == '?') sep='';
}
_url += sep + param;
return _url;
}
测试者:
/*
function addParameterToURL_TESTER_sub(_url,key,value){
//log(_url);
log(addParameterToURL(_url,key,value));
}
function addParameterToURL_TESTER(){
log('-------------------');
var _url ='www.google.com';
addParameterToURL_TESTER_sub(_url,'key','value');
addParameterToURL_TESTER_sub(_url,'key','Text Value');
_url ='www.google.com?';
addParameterToURL_TESTER_sub(_url,'key','value');
_url ='www.google.com?A=B';
addParameterToURL_TESTER_sub(_url,'key','value');
_url ='www.google.com?A=B&';
addParameterToURL_TESTER_sub(_url,'key','value');
_url ='www.google.com?A=1&B=2';
addParameterToURL_TESTER_sub(_url,'key','value');
}//*/
var MyApp = new Class();
MyApp.extend({
utility: {
queryStringHelper: function (url) {
var originalUrl = url;
var newUrl = url;
var finalUrl;
var insertParam = function (key, value) {
key = escape(key);
value = escape(value);
//The previous post had the substr strat from 1 in stead of 0!!!
var kvp = newUrl.substr(0).split('&');
var i = kvp.length;
var x;
while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) {
kvp[kvp.length] = [key, value].join('=');
}
finalUrl = kvp.join('&');
return finalUrl;
};
this.insertParameterToQueryString = insertParam;
this.insertParams = function (keyValues) {
for (var keyValue in keyValues[0]) {
var key = keyValue;
var value = keyValues[0][keyValue];
newUrl = insertParam(key, value);
}
return newUrl;
};
return this;
}
}
});
/** * Add a URL parameter * @param {string} url * @param {string} param the key to set * @param {string} value */ var addParam = function(url, param, value) { param = encodeURIComponent(param); var a = document.createElement('a'); param += (value ? "=" + encodeURIComponent(value) : ""); a.href = url; a.search += (a.search ? "&" : "") + param; return a.href; } /** * Add a URL parameter (or modify if already exists) * @param {string} url * @param {string} param the key to set * @param {string} value */ var addOrReplaceParam = function(url, param, value) { param = encodeURIComponent(param); var r = "([&?]|&)" + param + "\\b(?:=(?:[^&#]*))*"; var a = document.createElement('a'); var regex = new RegExp(r); var str = param + (value ? "=" + encodeURIComponent(value) : ""); a.href = url; var q = a.search.replace(regex, "$1"+str); if (q === a.search) { a.search += (a.search ? "&" : "") + str; } else { a.search = q; } return a.href; } url = "http://www.example.com#hashme"; newurl = addParam(url, "ciao", "1"); alert(newurl);
请注意,参数应该在被追加到查询字符串之前进行编码。
http://jsfiddle.net/48z7z4kx/
如果你在链接或其他地方弄乱了url,你可能也必须考虑哈希。这里有一个相当容易理解的解决方案。可能不是最快的,因为它使用正则表达式…但在99.999%的情况下,这种差异真的不重要!
function addQueryParam( url, key, val ){
var parts = url.match(/([^?#]+)(\?[^#]*)?(\#.*)?/);
var url = parts[1];
var qs = parts[2] || '';
var hash = parts[3] || '';
if ( !qs ) {
return url + '?' + key + '=' + encodeURIComponent( val ) + hash;
} else {
var qs_parts = qs.substr(1).split("&");
var i;
for (i=0;i<qs_parts.length;i++) {
var qs_pair = qs_parts[i].split("=");
if ( qs_pair[0] == key ){
qs_parts[ i ] = key + '=' + encodeURIComponent( val );
break;
}
}
if ( i == qs_parts.length ){
qs_parts.push( key + '=' + encodeURIComponent( val ) );
}
return url + '?' + qs_parts.join('&') + hash;
}
}
查看https://github.com/derek-watson/jsUri
Uri和javascript查询字符串操作。
这个项目结合了Steven Levithan的优秀parseUri正则表达式库。您可以安全地解析所有形状和大小的url,无论它们是多么无效或丑陋。
我是这么做的。使用我的editParams()函数,你可以添加,删除或更改任何参数,然后使用内置的replaceState()函数更新URL:
window.history.replaceState('object or string', 'Title', 'page.html' + editParams('enable', 'true'));
// 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;
}
有时我们看到?在URL结尾,我找到了一些解决方案,生成的结果为file.php?&foo=bar。我想出了我自己的解决方案,以完美地工作!
location.origin + location.pathname + location.search + (location.search=='' ? '?' : '&') + 'lang=ar'
注意:位置。origin不能在IE中工作,这里是它的修复。
这就是我在服务器端(如Node.js)添加或更新一些基本url参数时使用的方法。
CoffeScript:
### @method addUrlParam Adds parameter to a given url. If the parameter already exists in the url is being replaced. @param {string} url @param {string} key Parameter's key @param {string} value Parameter's value @returns {string} new url containing the parameter ### addUrlParam = (url, key, value) -> newParam = key+"="+value result = url.replace(new RegExp('(&|\\?)' + key + '=[^\&|#]*'), '$1' + newParam) if result is url result = if url.indexOf('?') != -1 then url.split('?')[0] + '?' + newParam + '&' + url.split('?')[1] else if url.indexOf('#') != -1 then url.split('#')[0] + '?' + newParam + '#' + url.split('#')[1] else url + '?' + newParam return result
JavaScript:
function addUrlParam(url, key, value) { var newParam = key+"="+value; var result = url.replace(new RegExp("(&|\\?)"+key+"=[^\&|#]*"), '$1' + newParam); if (result === url) { result = (url.indexOf("?") != -1 ? url.split("?")[0]+"?"+newParam+"&"+url.split("?")[1] : (url.indexOf("#") != -1 ? url.split("#")[0]+"?"+newParam+"#"+ url.split("#")[1] : url+'?'+newParam)); } return result; } var url = "http://www.example.com?foo=bar&ciao=3&doom=5#hashme"; result1.innerHTML = addUrlParam(url, "ciao", "1"); <p id="result1"></p>
如果你有一个url字符串,你想用一个参数来装饰,你可以试试这个在线程序:
urlstring += ( urlstring.match( /[\?]/g ) ? '&' : '?' ) + 'param=value';
这意味着什么?将是参数的前缀,但如果已经有?在urlstring中,than &将是前缀。
我也会建议做encodeURI(paramvariable),如果你没有硬编码参数,但它是在一个paramvariable;或者里面有有趣的角色。
encodeURI函数的使用请参见javascript URL编码。
以下功能将帮助您添加,更新和删除参数或从URL。
/ / example1and
var myURL = '/search';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search
/ / example2
var myURL = '/search?category=mobile';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile
/ /青年们
var myURL = '/search?location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search
/ / example4
var myURL = '/search?category=mobile&location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile
/ / example5
var myURL = 'https://example.com/search?location=texas#fragment';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california#fragment
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york#fragment
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search#fragment
这是函数。
function updateUrl(url,key,value){
if(value!==undefined){
value = encodeURI(value);
}
var hashIndex = url.indexOf("#")|0;
if (hashIndex === -1) hashIndex = url.length|0;
var urls = url.substring(0, hashIndex).split('?');
var baseUrl = urls[0];
var parameters = '';
var outPara = {};
if(urls.length>1){
parameters = urls[1];
}
if(parameters!==''){
parameters = parameters.split('&');
for(k in parameters){
var keyVal = parameters[k];
keyVal = keyVal.split('=');
var ekey = keyVal[0];
var evalue = '';
if(keyVal.length>1){
evalue = keyVal[1];
}
outPara[ekey] = evalue;
}
}
if(value!==undefined){
outPara[key] = value;
}else{
delete outPara[key];
}
parameters = [];
for(var k in outPara){
parameters.push(k + '=' + outPara[k]);
}
var finalUrl = baseUrl;
if(parameters.length>0){
finalUrl += '?' + parameters.join('&');
}
return finalUrl + url.substring(hashIndex);
}
就我所知,上面的答案都没有解决查询字符串包含参数的情况,这些参数本身就是一个数组,因此会出现不止一次,例如:
http://example.com?sizes[]=a&sizes[]=b
下面的函数是我用来更新document.location.search的。它接受一个键/值对数组作为参数,它将返回一个修改后的版本,你可以做任何你想做的事情。我是这样使用的:
var newParams = [
['test','123'],
['best','456'],
['sizes[]','XXL']
];
var newUrl = document.location.pathname + insertParams(newParams);
history.replaceState('', '', newUrl);
如果当前url为:
http://example.com/index.php?test=replaceme&sizes [] = XL
这会让你
http://example.com/index.php?test=123&sizes[]=XL&尺寸[]=XXL&best=456
函数
function insertParams(params) {
var result;
var ii = params.length;
var queryString = document.location.search.substr(1);
var kvps = queryString ? queryString.split('&') : [];
var kvp;
var skipParams = [];
var i = kvps.length;
while (i--) {
kvp = kvps[i].split('=');
if (kvp[0].slice(-2) != '[]') {
var ii = params.length;
while (ii--) {
if (params[ii][0] == kvp[0]) {
kvp[1] = params[ii][1];
kvps[i] = kvp.join('=');
skipParams.push(ii);
}
}
}
}
var ii = params.length;
while (ii--) {
if (skipParams.indexOf(ii) === -1) {
kvps.push(params[ii].join('='));
}
}
result = kvps.length ? '?' + kvps.join('&') : '';
return result;
}
你可以使用其中一个:
https://developer.mozilla.org/en-US/docs/Web/API/URL https://developer.mozilla.org/en/docs/Web/API/URLSearchParams
例子:
var url = new URL("http://foo.bar/?x=1&y=2");
// If your expected result is "http://foo.bar/?x=1&y=2&x=42"
url.searchParams.append('x', 42);
// If your expected result is "http://foo.bar/?x=42&y=2"
url.searchParams.set('x', 42);
你可以使用url。href或URL . tostring()来获取完整的URL
最简单的解决方案,工作,如果你已经有一个标签或没有,并自动删除它,所以它不会一直添加相等的标签,有乐趣
function changeURL(tag)
{
if(window.location.href.indexOf("?") > -1) {
if(window.location.href.indexOf("&"+tag) > -1){
var url = window.location.href.replace("&"+tag,"")+"&"+tag;
}
else
{
var url = window.location.href+"&"+tag;
}
}else{
if(window.location.href.indexOf("?"+tag) > -1){
var url = window.location.href.replace("?"+tag,"")+"?"+tag;
}
else
{
var url = window.location.href+"?"+tag;
}
}
window.location = url;
}
THEN
changeURL("i=updated");
这是一个添加查询参数的简单方法:
const query = new URLSearchParams(window.location.search);
query.append("enabled", "true");
这就是这里更多的内容。
请注意支持规格。
试一试 正则表达式,如此之慢,因此:
var SetParamUrl = function(_k, _v) {// replace and add new parameters
let arrParams = window.location.search !== '' ? decodeURIComponent(window.location.search.substr(1)).split('&').map(_v => _v.split('=')) : Array();
let index = arrParams.findIndex((_v) => _v[0] === _k);
index = index !== -1 ? index : arrParams.length;
_v === null ? arrParams = arrParams.filter((_v, _i) => _i != index) : arrParams[index] = [_k, _v];
let _search = encodeURIComponent(arrParams.map(_v => _v.join('=')).join('&'));
let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + (arrParams.length > 0 ? '?' + _search : '');
// window.location = newurl; //reload
if (history.pushState) { // without reload
window.history.pushState({path:newurl}, null, newurl);
}
};
var GetParamUrl = function(_k) {// get parameter by key
let sPageURL = decodeURIComponent(window.location.search.substr(1)),
sURLVariables = sPageURL.split('&').map(_v => _v.split('='));
let _result = sURLVariables.find(_v => _v[0] === _k);
return _result[1];
};
例子:
// https://some.com/some_path
GetParamUrl('cat');//undefined
SetParamUrl('cat', "strData");// https://some.com/some_path?cat=strData
GetParamUrl('cat');//strData
SetParamUrl('sotr', "strDataSort");// https://some.com/some_path?cat=strData&sotr=strDataSort
GetParamUrl('sotr');//strDataSort
SetParamUrl('cat', "strDataTwo");// https://some.com/some_path?cat=strDataTwo&sotr=strDataSort
GetParamUrl('cat');//strDataTwo
//remove param
SetParamUrl('cat', null);// https://some.com/some_path?sotr=strDataSort
随着JS的新成就,这里是如何将查询参数添加到URL:
var protocol = window.location.protocol,
host = '//' + window.location.host,
path = window.location.pathname,
query = window.location.search;
var newUrl = protocol + host + path + query + (query ? '&' : '?') + 'param=1';
window.history.pushState({path:newUrl}, '' , newUrl);
还有这种可能性Moziila URLSearchParams.append()
这将在所有现代浏览器中工作。
function insertParam(key,value) {
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' +key+'='+value;
window.history.pushState({path:newurl},'',newurl);
}
}
Vianney Bajart的答案是正确的;然而,URL只会工作,如果你有完整的URL端口,主机,路径和查询:
new URL('http://server/myapp.php?id=10&enabled=true')
URLSearchParams只会在你只传递查询字符串时起作用:
new URLSearchParams('?id=10&enabled=true')
如果你有一个不完整或相对的URL,不关心的基础URL,你可以通过?获取查询字符串,然后像这样连接:
function setUrlParams(url, key, value) {
url = url.split('?');
usp = new URLSearchParams(url[1]);
usp.set(key, value);
url[1] = usp.toString();
return url.join('?');
}
let url = 'myapp.php?id=10';
url = setUrlParams(url, 'enabled', true); // url = 'myapp.php?id=10&enabled=true'
url = setUrlParams(url, 'id', 11); // url = 'myapp.php?id=11&enabled=true'
Internet Explorer浏览器不兼容。
加入@Vianney的回答https://stackoverflow.com/a/44160941/6609678
我们可以导入node中的内置URL模块,如下所示
const { URL } = require('url');
例子:
Terminal $ node
> const { URL } = require('url');
undefined
> let url = new URL('', 'http://localhost:1989/v3/orders');
undefined
> url.href
'http://localhost:1989/v3/orders'
> let fetchAll=true, timePeriod = 30, b2b=false;
undefined
> url.href
'http://localhost:1989/v3/orders'
> url.searchParams.append('fetchAll', fetchAll);
undefined
> url.searchParams.append('timePeriod', timePeriod);
undefined
> url.searchParams.append('b2b', b2b);
undefined
> url.href
'http://localhost:1989/v3/orders?fetchAll=true&timePeriod=30&b2b=false'
> url.toString()
'http://localhost:1989/v3/orders?fetchAll=true&timePeriod=30&b2b=false'
有用的链接:
https://developer.mozilla.org/en-US/docs/Web/API/URL https://developer.mozilla.org/en/docs/Web/API/URLSearchParams
你可以使用URLSearchParams
const urlParams = new URLSearchParams(window.location.search);
urlParams.set('order', 'date');
window.location.search = urlParams;
.第一个农业是关键,第二个是价值。
注意:这在任何版本的ie浏览器中都不支持(但在Edge中支持)
重置所有查询字符串
Var params = {params:"val1", params:"val2"}; 让str = jQuery.param(参数); let uri = window.location. reff . tostring (); if (uri.indexOf("?") > 0) Uri = Uri。substring (0, uri.indexOf(“?”); console.log (uri +”?”+ str); / / window.location。Href = uri+"?"+str; < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本>
试试这个。
// uses the URL class
function setParam(key, value) {
let url = new URL(window.document.location);
let params = new URLSearchParams(url.search.slice(1));
if (params.has(key)) {
params.set(key, value);
}else {
params.append(key, value);
}
}
它处理这样的URL:
空 没有任何参数 已经有一些参数 有什么?在最后,但同时没有任何参数
它不处理这样的URL:
带有片段标识符(即散列,#) 如果URL已经有必要的查询参数(那么将会有重复)
适用于:
Chrome 32 + 火狐26 + 野生动物园7.1 +
function appendQueryParameter(url, name, value) {
if (url.length === 0) {
return;
}
let rawURL = url;
// URL with `?` at the end and without query parameters
// leads to incorrect result.
if (rawURL.charAt(rawURL.length - 1) === "?") {
rawURL = rawURL.slice(0, rawURL.length - 1);
}
const parsedURL = new URL(rawURL);
let parameters = parsedURL.search;
parameters += (parameters.length === 0) ? "?" : "&";
parameters = (parameters + name + "=" + value);
return (parsedURL.origin + parsedURL.pathname + parameters);
}
使用ES6模板字符串的版本。
适用于:
Chrome 41 + 火狐32 + 野生动物园9.1 +
function appendQueryParameter(url, name, value) {
if (url.length === 0) {
return;
}
let rawURL = url;
// URL with `?` at the end and without query parameters
// leads to incorrect result.
if (rawURL.charAt(rawURL.length - 1) === "?") {
rawURL = rawURL.slice(0, rawURL.length - 1);
}
const parsedURL = new URL(rawURL);
let parameters = parsedURL.search;
parameters += (parameters.length === 0) ? "?" : "&";
parameters = `${parameters}${name}=${value}`;
return `${parsedURL.origin}${parsedURL.pathname}${parameters}`;
}
在URL类中有一个内置函数,你可以使用它来轻松处理查询字符串的键/值参数:
const url = new URL(window.location.href);
// url.searchParams has several function, we just use `set` function
// to set a value, if you just want to append without replacing value
// let use `append` function
url.searchParams.set('key', 'value');
console.log(url.search) // <== '?key=value'
// if window.location.href has already some qs params this `set` function
// modify or append key/value in it
有关searchParams函数的更多信息。
IE不支持URL,请检查兼容性
此解决方案使用更新的搜索参数更新窗口的当前URL,而无需实际重新加载页面。这种方法在PWA/SPA上下文中很有用。
function setURLSearchParam(key, value) {
const url = new URL(window.location.href);
url.searchParams.set(key, value);
window.history.pushState({ path: url.href }, '', url.href);
}
以下几点:
合并重复的查询字符串参数 使用绝对和相对url 在浏览器和节点中工作
/**
* Adds query params to existing URLs (inc merging duplicates)
* @param {string} url - src URL to modify
* @param {object} params - key/value object of params to add
* @returns {string} modified URL
*/
function addQueryParamsToUrl(url, params) {
// if URL is relative, we'll need to add a fake base
var fakeBase = !url.startsWith('http') ? 'http://fake-base.com' : undefined;
var modifiedUrl = new URL(url || '', fakeBase);
// add/update params
Object.keys(params).forEach(function(key) {
if (modifiedUrl.searchParams.has(key)) {
modifiedUrl.searchParams.set(key, params[key]);
}
else {
modifiedUrl.searchParams.append(key, params[key]);
}
});
// return as string (remove fake base if present)
return modifiedUrl.toString().replace(fakeBase, '');
}
例子:
// returns /guides?tag=api
addQueryParamsToUrl('/guides?tag=hardware', { tag:'api' })
// returns https://orcascan.com/guides?tag=api
addQueryParamsToUrl('https://orcascan.com/guides?tag=hardware', { tag: 'api' })
const params = new URLSearchParams(window.location.search);
params.delete(key)
window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
我添加我的解决方案,因为它支持相对url除了绝对url。在其他方面,它与顶部的答案相同,后者也使用Web API。
/**
* updates a relative or absolute
* by setting the search query with
* the passed key and value.
*/
export const setQueryParam = (url, key, value) => {
const dummyBaseUrl = 'https://dummy-base-url.com';
const result = new URL(url, dummyBaseUrl);
result.searchParams.set(key, value);
return result.toString().replace(dummyBaseUrl, '');
};
还有人开玩笑说:
// some jest tests
describe('setQueryParams', () => {
it('sets param on relative url with base path', () => {
// act
const actual = setQueryParam(
'/', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('/?ref=some-value');
});
it('sets param on relative url with no path', () => {
// act
const actual = setQueryParam(
'', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('/?ref=some-value');
});
it('sets param on relative url with some path', () => {
// act
const actual = setQueryParam(
'/some-path', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('/some-path?ref=some-value');
});
it('overwrites existing param', () => {
// act
const actual = setQueryParam(
'/?ref=prev-value', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('/?ref=some-value');
});
it('sets param while another param exists', () => {
// act
const actual = setQueryParam(
'/?other-param=other-value', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('/?other-param=other-value&ref=some-value');
});
it('honors existing base url', () => {
// act
const actual = setQueryParam(
'https://base.com', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('https://base.com/?ref=some-value');
});
it('honors existing base url with some path', () => {
// act
const actual = setQueryParam(
'https://base.com/some-path', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('https://base.com/some-path?ref=some-value');
});
});