In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:
在使用AJAX调用的web应用程序中,我需要提交一个请求,但将一个参数添加到URL的末尾,例如:
Original URL:
原始URL:
http://server/myapp.php?id=10
Resulting URL:
导致的网址:
http://server/myapp.php?id=10&enabled=true
http://server/myapp.php?id=10&enabled=true
Looking for a JavaScript function which parses the URL looking at each parameter, then adds the new parameter or updates the value if one already exists.
寻找一个JavaScript函数,它解析每个参数的URL,然后添加新的参数或者更新已经存在的值。
26 个解决方案
#1
150
A basic implementation which you'll need to adapt would look something like this:
你需要适应的一个基本实现是这样的:
function insertParam(key, value)
{
key = encodeURI(key); value = encodeURI(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
document.location.search = kvp.join('&');
}
This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match
这大约是regex或基于搜索的解决方案的两倍,但这完全取决于querystring的长度和任何匹配的索引。
the slow regex method I benchmarked against for completions sake (approx +150% slower)
我用慢的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;
}
#2
57
Thank you all for your contribution. I used annakata code and modified to also include the case where there is no query string in the url at all. Hope this would help.
谢谢你们的贡献。我使用了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('&');
}
}
#3
53
Using:
使用:
- https://developer.mozilla.org/en-US/docs/Web/API/URL
- https://developer.mozilla.org/en-US/docs/Web/API/URL
- https://developer.mozilla.org/fr/docs/Web/API/URLSearchParams
- https://developer.mozilla.org/fr/docs/Web/API/URLSearchParams
Example:
例子:
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);
#4
48
This is very simple solution. Its doesn't control parameter existence, and it doesn't change existing value. It adds your parameter to end, so you can get latest value in your back-end code.
这是一个很简单的解。它不控制参数的存在,它不会改变现有的值。它将您的参数添加到end,以便在后端代码中获得最新的值。
function addParameterToURL(param){
_url = location.href;
_url += (_url.split('?')[1] ? '&':'?') + param;
return _url;
}
#5
29
Here's a vastly simplified version, making tradeoffs for legibility and fewer lines of code instead of micro-optimized performance (and we're talking about a few miliseconds difference, realistically... due to the nature of this (operating on the current document's location), this will most likely be ran once on a page).
这里有一个大大简化的版本,为易读性和更少的代码行做了权衡,而不是微优化的性能(我们讨论的是几毫秒的差别,实际上……)由于这个特性(在当前文档的位置上操作),很可能会在页面上运行一次。
/**
* 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;
};
You would then use this like so:
你可以这样使用:
document.location.pathname + addUrlParam(document.location.search, 'foo', 'bar');
#6
18
I have a 'class' that does this and here it is:
我有一个这样的类,它是:
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 );
I have overridden the toString method so there is no need to call QS::getQueryString, you can use QS::toString or, as I have done in the examples just rely on the object being coerced into a string.
我已经重写了toString方法,因此不需要调用QS::getQueryString,您可以使用QS::toString或,就像我在示例中所做的那样,仅仅依赖于被强制转换成字符串的对象。
#7
16
/**
* 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);
And please note that parameters should be encoded before being appended in query string.
请注意,参数在被追加到查询字符串之前应该被编码。
http://jsfiddle.net/48z7z4kx/
#8
6
Sometime we see ?
at the end URL, i found some solutions which generate results as file.php?&foo=bar
. i came up with my own solution work perfectly as i want!
有时我们看到了什么?在最终的URL中,我找到了一些作为file.php?&foo=bar生成结果的解决方案。我想出了我自己的解决方案。
location.origin + location.pathname + location.search + (location.search=='' ? '?' : '&') + 'lang=ar'
Note: location.origin doesn't work in IE, here is its fix.
注意:位置。原点在IE中不起作用,这是它的修正。
#9
6
If you have a string with url that you want to decorate with a param, you could try this:
如果你有一个带url的字符串,你想用一个param来装饰,你可以试试这个:
urlstring += ( urlstring.match( /[\?]/g ) ? '&' : '?' ) + 'param=value';
This means that ? will be the prefix of the parameter, but if you already have ? in urlstring
, than & will be the prefix.
这意味着?将是参数的前缀,但如果已经有了?在urlstring中,而不是&将是前缀。
I would also recommend to do encodeURI( paramvariable )
if you didn't hardcoded parameter, but it is inside a paramvariable
; or if you have funny characters in it.
如果没有硬编码参数,我还建议使用encodeURI(paramvariable),但它在一个参数中;或者如果你有有趣的角色。
See javascript URL Encoding for usage of the encodeURI
function.
请参阅javascript URL编码以使用encodeURI函数。
#10
4
Check out https://github.com/derek-watson/jsUri
看看https://github.com/derek-watson/jsUri
Uri and query string manipulation in javascript.
Uri和javascript中的查询字符串操作。
This project incorporates the excellent parseUri regular expression library by Steven Levithan. You can safely parse URLs of all shapes and sizes, however invalid or hideous.
该项目整合了Steven Levithan的优秀parseUri正则表达式库。您可以安全地解析各种形状和大小的url,无论它们是无效的还是难看的。
#11
3
This is what I use when it comes to some basic url param additions or updates on the server-side like Node.js.
这是我在一些基本的url param添加或服务器端(比如Node.js)上的更新时所使用的。
CoffeScript:
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:
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>
#12
2
This was my own attempt, but I'll use the answer by annakata as it seems much cleaner:
这是我自己的尝试,但我将会用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;
}
Also, I found this jQuery plugin from another post on *, and if you need more flexibility you could use that: http://plugins.jquery.com/project/query-object
另外,我在*的另一个帖子中发现了这个jQuery插件,如果您需要更多的灵活性,您可以使用它:http://plugins.jquery.com/project/queryobject。
I would think the code would be (haven't tested):
我认为代码是(还没有测试):
return $.query.parse(sourceUrl).set(parameterName, parameterValue).toString();
#13
2
I would go with this small but complete library to handle urls in js:
我将使用这个小而完整的库来处理js中的url:
https://github.com/Mikhus/jsurl
https://github.com/Mikhus/jsurl
#14
2
Following function will help you to add,update and delete parameters to or from URL
以下功能将帮助您添加、更新和删除URL的参数。
//example1
/ /例二
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
/ / 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
//example3
/ /青年们
var myURL = '/search?location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('updated 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
/ / example4
var myURL = '/search?category=mobile&location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('updated 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
Here is the function
这是函数
function updateUrl(url,key,value){
if(value!=undefined){
value = encodeURI(value);
}
var urls = url.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 eval = '';
if(keyVal.length>1){
eval = keyVal[1];
}
outPara[ekey] = eval;
}
}
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;
}
#15
2
This is a simple way to add a query parameter:
这是添加查询参数的简单方法:
const query = new URLSearchParams(window.location.search);
query.append("enabled", "true");
And that is it more here
这里更多。
Thanks, T04435
谢谢,T04435
#16
1
I like the answer of Mehmet Fatih Yıldız even he did not answer the whole question.
我喜欢的答案*Fatih Yıldız即使他没有回答这个问题。
In the same line as his answer, I use this code:
在他的回答中,我用了这段代码:
"Its doesn't control parameter existence, and it doesn't change existing value. It adds your parameter to the end"
“它不控制参数的存在,也不改变现有的值。它将你的参数添加到末尾"
/** 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;
}
and the tester:
和测试人员:
/*
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');
}//*/
#17
0
Ok here I compare Two functions, one made by myself (regExp) and another one made by (annakata).
这里我比较两个函数,一个是我自己做的(regExp),另一个是(annakata)做的。
Split array:
将数组:
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('&');
}
Regexp method:
正则表达式的方法:
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;
}
Testing case:
测试用例:
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));
It seems that even with simplest solution (when regexp use only test and do not enter .replace function) it is still slower than spliting... Well. Regexp is kinda slow but... uhh...
看起来,即使使用最简单的解决方案(regexp只使用测试而不输入.replace函数),它仍然比分割要慢……好。Regexp有点慢,但是…喔…
#18
0
If you're messing around with urls in links or somewhere else, you may have to take the hash into account as well. Here's a fairly simple to understand solution. Probably not the FASTEST since it uses a regex... but in 99.999% of cases, the difference really doesn't matter!
如果您在链接或其他地方使用url,那么您可能也需要考虑散列。这里有一个相当简单的解决方案。可能不是最快的,因为它使用了regex…但在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;
}
}
#19
0
The simplest solution I can think of is this method, which will return the modified URI. I feel like most of you are working way too hard.
我能想到的最简单的解决方案是这个方法,它将返回已修改的URI。我觉得你们大多数人工作太辛苦了。
function setParam(uri, key, val) {
return uri
.replace(new RegExp("([?&]"+key+"(?=[=&#]|$)[^#&]*|(?=#|$))"), "&"+key+"="+encodeURIComponent(val))
.replace(/^([^?&]+)&/, "$1?");
}
#20
0
As best I can tell none of the above answers address the case where the query string contains parameters which are themselves an array and hence will appear more than once, e.g:
最好的情况是,上面的答案都不能解决查询字符串包含参数的情况,这些参数本身就是一个数组,因此会出现不止一次,例如:
http://example.com?sizes[]=a&sizes[]=b
The following function is what I wrote to update document.location.search
. It takes an array of key/value pair arrays as an argument and it will return a revised version of the latter which you can do whatever you'd like with. I'm using it like this:
下面的函数是我写的用来更新document。location。search。它以一个键/值对数组的数组作为参数,它将返回一个修改后的版本,您可以任意使用它。我是这样使用的:
var newParams = [
['test','123'],
['best','456'],
['sizes[]','XXL']
];
var newUrl = document.location.pathname + insertParams(newParams);
history.replaceState('', '', newUrl);
If the current url was:
如果当前的url是:
http://example.com/index.php?test=replaceme&sizes[]=XL
http://example.com/index.php?test=replaceme&sizes[]= XL
This would get you
这将让你
http://example.com/index.php?test=123&sizes[]=XL&sizes[]=XXL&best=456
http://example.com/index.php?test=123&sizes[]= XL&sizes[]= XXL&best = 456
Function
函数
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;
}
#21
0
Try
The regular expressions, so slow, thus:
尝试正则表达式,所以要慢,这样:
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];
};
Example:
例子:
// 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
#22
0
Easiest solution, works if you have already a tag or not, and removes it automatically so it wont keep adding equal tags, have fun
最简单的解决方法是,如果你已经有一个标签或者没有标签,并且自动删除它,这样它就不会继续添加相等的标签了。
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");
#23
0
With the new achievements in JS here is how one can add query param to the URL:
在JS的新成就中,我们可以向URL添加查询param:
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);
Also see this possibility Moziila URLSearchParams.append()
也可以看到Moziila URLSearchParams.append()
#24
0
This will work in all modern browsers.
这将适用于所有的现代浏览器。
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);
}
}
#25
-1
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;
}
}
});
#26
-1
Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the 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;
}
#1
150
A basic implementation which you'll need to adapt would look something like this:
你需要适应的一个基本实现是这样的:
function insertParam(key, value)
{
key = encodeURI(key); value = encodeURI(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
document.location.search = kvp.join('&');
}
This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match
这大约是regex或基于搜索的解决方案的两倍,但这完全取决于querystring的长度和任何匹配的索引。
the slow regex method I benchmarked against for completions sake (approx +150% slower)
我用慢的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;
}
#2
57
Thank you all for your contribution. I used annakata code and modified to also include the case where there is no query string in the url at all. Hope this would help.
谢谢你们的贡献。我使用了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('&');
}
}
#3
53
Using:
使用:
- https://developer.mozilla.org/en-US/docs/Web/API/URL
- https://developer.mozilla.org/en-US/docs/Web/API/URL
- https://developer.mozilla.org/fr/docs/Web/API/URLSearchParams
- https://developer.mozilla.org/fr/docs/Web/API/URLSearchParams
Example:
例子:
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);
#4
48
This is very simple solution. Its doesn't control parameter existence, and it doesn't change existing value. It adds your parameter to end, so you can get latest value in your back-end code.
这是一个很简单的解。它不控制参数的存在,它不会改变现有的值。它将您的参数添加到end,以便在后端代码中获得最新的值。
function addParameterToURL(param){
_url = location.href;
_url += (_url.split('?')[1] ? '&':'?') + param;
return _url;
}
#5
29
Here's a vastly simplified version, making tradeoffs for legibility and fewer lines of code instead of micro-optimized performance (and we're talking about a few miliseconds difference, realistically... due to the nature of this (operating on the current document's location), this will most likely be ran once on a page).
这里有一个大大简化的版本,为易读性和更少的代码行做了权衡,而不是微优化的性能(我们讨论的是几毫秒的差别,实际上……)由于这个特性(在当前文档的位置上操作),很可能会在页面上运行一次。
/**
* 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;
};
You would then use this like so:
你可以这样使用:
document.location.pathname + addUrlParam(document.location.search, 'foo', 'bar');
#6
18
I have a 'class' that does this and here it is:
我有一个这样的类,它是:
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 );
I have overridden the toString method so there is no need to call QS::getQueryString, you can use QS::toString or, as I have done in the examples just rely on the object being coerced into a string.
我已经重写了toString方法,因此不需要调用QS::getQueryString,您可以使用QS::toString或,就像我在示例中所做的那样,仅仅依赖于被强制转换成字符串的对象。
#7
16
/**
* 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);
And please note that parameters should be encoded before being appended in query string.
请注意,参数在被追加到查询字符串之前应该被编码。
http://jsfiddle.net/48z7z4kx/
#8
6
Sometime we see ?
at the end URL, i found some solutions which generate results as file.php?&foo=bar
. i came up with my own solution work perfectly as i want!
有时我们看到了什么?在最终的URL中,我找到了一些作为file.php?&foo=bar生成结果的解决方案。我想出了我自己的解决方案。
location.origin + location.pathname + location.search + (location.search=='' ? '?' : '&') + 'lang=ar'
Note: location.origin doesn't work in IE, here is its fix.
注意:位置。原点在IE中不起作用,这是它的修正。
#9
6
If you have a string with url that you want to decorate with a param, you could try this:
如果你有一个带url的字符串,你想用一个param来装饰,你可以试试这个:
urlstring += ( urlstring.match( /[\?]/g ) ? '&' : '?' ) + 'param=value';
This means that ? will be the prefix of the parameter, but if you already have ? in urlstring
, than & will be the prefix.
这意味着?将是参数的前缀,但如果已经有了?在urlstring中,而不是&将是前缀。
I would also recommend to do encodeURI( paramvariable )
if you didn't hardcoded parameter, but it is inside a paramvariable
; or if you have funny characters in it.
如果没有硬编码参数,我还建议使用encodeURI(paramvariable),但它在一个参数中;或者如果你有有趣的角色。
See javascript URL Encoding for usage of the encodeURI
function.
请参阅javascript URL编码以使用encodeURI函数。
#10
4
Check out https://github.com/derek-watson/jsUri
看看https://github.com/derek-watson/jsUri
Uri and query string manipulation in javascript.
Uri和javascript中的查询字符串操作。
This project incorporates the excellent parseUri regular expression library by Steven Levithan. You can safely parse URLs of all shapes and sizes, however invalid or hideous.
该项目整合了Steven Levithan的优秀parseUri正则表达式库。您可以安全地解析各种形状和大小的url,无论它们是无效的还是难看的。
#11
3
This is what I use when it comes to some basic url param additions or updates on the server-side like Node.js.
这是我在一些基本的url param添加或服务器端(比如Node.js)上的更新时所使用的。
CoffeScript:
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:
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>
#12
2
This was my own attempt, but I'll use the answer by annakata as it seems much cleaner:
这是我自己的尝试,但我将会用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;
}
Also, I found this jQuery plugin from another post on *, and if you need more flexibility you could use that: http://plugins.jquery.com/project/query-object
另外,我在*的另一个帖子中发现了这个jQuery插件,如果您需要更多的灵活性,您可以使用它:http://plugins.jquery.com/project/queryobject。
I would think the code would be (haven't tested):
我认为代码是(还没有测试):
return $.query.parse(sourceUrl).set(parameterName, parameterValue).toString();
#13
2
I would go with this small but complete library to handle urls in js:
我将使用这个小而完整的库来处理js中的url:
https://github.com/Mikhus/jsurl
https://github.com/Mikhus/jsurl
#14
2
Following function will help you to add,update and delete parameters to or from URL
以下功能将帮助您添加、更新和删除URL的参数。
//example1
/ /例二
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
/ / 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
//example3
/ /青年们
var myURL = '/search?location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('updated 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
/ / example4
var myURL = '/search?category=mobile&location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('updated 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
Here is the function
这是函数
function updateUrl(url,key,value){
if(value!=undefined){
value = encodeURI(value);
}
var urls = url.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 eval = '';
if(keyVal.length>1){
eval = keyVal[1];
}
outPara[ekey] = eval;
}
}
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;
}
#15
2
This is a simple way to add a query parameter:
这是添加查询参数的简单方法:
const query = new URLSearchParams(window.location.search);
query.append("enabled", "true");
And that is it more here
这里更多。
Thanks, T04435
谢谢,T04435
#16
1
I like the answer of Mehmet Fatih Yıldız even he did not answer the whole question.
我喜欢的答案*Fatih Yıldız即使他没有回答这个问题。
In the same line as his answer, I use this code:
在他的回答中,我用了这段代码:
"Its doesn't control parameter existence, and it doesn't change existing value. It adds your parameter to the end"
“它不控制参数的存在,也不改变现有的值。它将你的参数添加到末尾"
/** 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;
}
and the tester:
和测试人员:
/*
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');
}//*/
#17
0
Ok here I compare Two functions, one made by myself (regExp) and another one made by (annakata).
这里我比较两个函数,一个是我自己做的(regExp),另一个是(annakata)做的。
Split array:
将数组:
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('&');
}
Regexp method:
正则表达式的方法:
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;
}
Testing case:
测试用例:
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));
It seems that even with simplest solution (when regexp use only test and do not enter .replace function) it is still slower than spliting... Well. Regexp is kinda slow but... uhh...
看起来,即使使用最简单的解决方案(regexp只使用测试而不输入.replace函数),它仍然比分割要慢……好。Regexp有点慢,但是…喔…
#18
0
If you're messing around with urls in links or somewhere else, you may have to take the hash into account as well. Here's a fairly simple to understand solution. Probably not the FASTEST since it uses a regex... but in 99.999% of cases, the difference really doesn't matter!
如果您在链接或其他地方使用url,那么您可能也需要考虑散列。这里有一个相当简单的解决方案。可能不是最快的,因为它使用了regex…但在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;
}
}
#19
0
The simplest solution I can think of is this method, which will return the modified URI. I feel like most of you are working way too hard.
我能想到的最简单的解决方案是这个方法,它将返回已修改的URI。我觉得你们大多数人工作太辛苦了。
function setParam(uri, key, val) {
return uri
.replace(new RegExp("([?&]"+key+"(?=[=&#]|$)[^#&]*|(?=#|$))"), "&"+key+"="+encodeURIComponent(val))
.replace(/^([^?&]+)&/, "$1?");
}
#20
0
As best I can tell none of the above answers address the case where the query string contains parameters which are themselves an array and hence will appear more than once, e.g:
最好的情况是,上面的答案都不能解决查询字符串包含参数的情况,这些参数本身就是一个数组,因此会出现不止一次,例如:
http://example.com?sizes[]=a&sizes[]=b
The following function is what I wrote to update document.location.search
. It takes an array of key/value pair arrays as an argument and it will return a revised version of the latter which you can do whatever you'd like with. I'm using it like this:
下面的函数是我写的用来更新document。location。search。它以一个键/值对数组的数组作为参数,它将返回一个修改后的版本,您可以任意使用它。我是这样使用的:
var newParams = [
['test','123'],
['best','456'],
['sizes[]','XXL']
];
var newUrl = document.location.pathname + insertParams(newParams);
history.replaceState('', '', newUrl);
If the current url was:
如果当前的url是:
http://example.com/index.php?test=replaceme&sizes[]=XL
http://example.com/index.php?test=replaceme&sizes[]= XL
This would get you
这将让你
http://example.com/index.php?test=123&sizes[]=XL&sizes[]=XXL&best=456
http://example.com/index.php?test=123&sizes[]= XL&sizes[]= XXL&best = 456
Function
函数
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;
}
#21
0
Try
The regular expressions, so slow, thus:
尝试正则表达式,所以要慢,这样:
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];
};
Example:
例子:
// 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
#22
0
Easiest solution, works if you have already a tag or not, and removes it automatically so it wont keep adding equal tags, have fun
最简单的解决方法是,如果你已经有一个标签或者没有标签,并且自动删除它,这样它就不会继续添加相等的标签了。
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");
#23
0
With the new achievements in JS here is how one can add query param to the URL:
在JS的新成就中,我们可以向URL添加查询param:
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);
Also see this possibility Moziila URLSearchParams.append()
也可以看到Moziila URLSearchParams.append()
#24
0
This will work in all modern browsers.
这将适用于所有的现代浏览器。
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);
}
}
#25
-1
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;
}
}
});
#26
-1
Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the 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;
}