如何使用Javascript/jQuery在URL中添加或替换查询参数?

时间:2021-05-01 10:28:31

I'm using jQuery 1.12. I want to replace a query string parameter in my window's URL query string, or add the parameter if it didn't exist before. I tried the below:

我使用jQuery 1.12。我想在窗口的URL查询字符串中替换一个查询字符串参数,或者添加一个以前不存在的参数。我试着以下:

new_url = window.location.href.replace( /[\?#].*|$/, "?order_by=" + data_val )  
window.location.href = new_url 

but what I'm discovering is that this wipes out all previous parameters in teh query string, which I don't want. If the query string is:

但我发现,这抹掉了teh查询字符串中所有先前的参数,这是我不想要的。如果查询字符串为:

?a=1&b=2

I would want the new query string to be:

我希望新的查询字符串为:

?a=2&b=2&order_by=data

and if the query string was:

如果查询字符串为:

?a=2&b=3&order_by=old_data

it would become:

它将成为:

?a=2&b=3&order_by=data

9 个解决方案

#1


3  

You could use a jQuery plugin to do the all the heavy lifting for you. It will parse the query string, and also reconstruct the updated query string for you. Much less code to deal with.

您可以使用jQuery插件来完成所有繁重的工作。它将解析查询字符串,并为您重构更新后的查询字符串。更少的代码需要处理。

Plugin Download Page
Github Repo

插件下载页面Github Repo

// URL: ?a=2&b=3&order_by=old_data

var order_by = $.query.get('order_by');
//=> old_data

// Conditionally modify parameter value
if (order_by) { 
  order_by = “data”;
}

// Inject modified parameter back into query string
var newUrl = $.query.set(“order_by”, order_by).toString();
//=> ?a=2&b=3&order_by=data

For those using Node.js, there is a package for this available in NPM.

对于那些使用节点。js, NPM中有一个包。

NPM Package
Github Repo

NPM包Github回购

var queryString = require('query-string');
var parsed = queryString.parse('?a=2&b=3&order_by=old_data');  // location.search

// Conditionally modify parameter value
if (parsed.order_by) {
  parsed.order_by = 'data';
}

// Inject modified parameter back into query string
const newQueryString = queryString.stringify(parsed);
//=> a=2&b=3&order_by=data

#2


4  

A good solution ought to handle all of the following:

一个好的解决方案应该处理以下所有问题:

  1. A URL that already has an order_by query parameter, optionally with whitespace before the equals sign. This can be further divided into cases where the order_by appears at the start, middle or end of the query string.
  2. 具有order_by查询参数的URL,可选地在等号之前使用空格。这可以进一步划分为order_by出现在查询字符串的开头、中间或结尾的情况。
  3. A URL that doesn't already have and order_by query parameter but does already have a question mark to delimit the query string.
  4. 一个URL,它没有查询参数order_by,但是已经有一个问号来分隔查询字符串。
  5. A URL that doesn't already have and order_by query parameter and doesn't already have a question mark to delimit the query string.
  6. 一个URL,它没有查询参数order_by,也没有问号来分隔查询字符串。

The following will handle the cases above:

以下将处理上述情况:

  if (/[?&]order_by\s*=/.test(oldUrl)) {
    newUrl = oldUrl.replace(/(?:([?&])order_by\s*=[^?&]*)/, "$1order_by=" + data_val);
  } else if (/\?/.test(oldUrl)) {
    newUrl = oldUrl + "&order_by=" + data_val;
  } else {
    newUrl = oldUrl + "?order_by=" + data_val;
  }

as demonstrated below:

如下证明:

getNewUrl("?a=1&b=2");
getNewUrl("?a=2&b=3&order_by=old_data");
getNewUrl("?a=2&b=3&order_by = old_data&c=4");
getNewUrl("?order_by=old_data&a=2&b=3");
getNewUrl("http://www.*.com");

function getNewUrl(oldUrl) {
  var data_val = "new_data";
  var newUrl;
  if (/[?&]order_by\s*=/.test(oldUrl)) {
    newUrl = oldUrl.replace(/(?:([?&])order_by\s*=[^?&]*)/, "$1order_by=" + data_val);
  } else if (/\?/.test(oldUrl)) {
    newUrl = oldUrl + "&order_by=" + data_val;
  } else {
    newUrl = oldUrl + "?order_by=" + data_val;
  }
  console.log(oldUrl + "\n...becomes...\n" + newUrl);
}  

#3


3  

function addOrReplaceOrderBy(newData) {
  var stringToAdd = "order_by=" + newData;

  if (window.location.search == "")
    return window.location.href + stringToAdd;

  if (window.location.search.indexOf('order_by=') == -1)
    return window.location.href + stringToAdd;

  var newSearchString = "";
  var searchParams = window.location.search.substring(1).split("&");
  for (var i = 0; i < searchParams.length; i++) {
    if (searchParams[i].indexOf('order_by=') > -1) {
      searchParams[i] = "order_by=" + newData;
      break;
    }
  }
  return window.location.href.split("?")[0] + "?" + searchParams.join("&");
}

window.location.href = addOrReplaceOrderBy("new_order_by");

A little long but I think it works as intended.

有一点长,但我认为它是想要的。

#4


1  

something like this?

是这样的吗?

new_url = "";

if(window.location.search && window.location.search.indexOf('order_by=') != -1)
  new_url = window.location.search.replace( /order_by=\w*\d*/, "order_by=" + data_val);
else if(window.location.search)
  new_url = window.location.search + "&order_by=" + data_val;
else
  new_url = window.location.search + "?order_by=" + data_val;

window.location.href = new_url;

#5


1  

You can remove parameter from query string using URLSearchParams https://developer.mozilla.org/ru/docs/Web/API/URLSearchParams?param11=val

您可以使用URLSearchParams从查询字符串中删除参数https://developer.mozilla.org/ru/docs/web/api/urlsearchparams? params?

It is not yet supported by IE and Safari, but you can use it by adding polyfill https://github.com/jerrybendy/url-search-params-polyfill

IE和Safari还不支持它,但是可以通过添加polyfill来使用它:https://github.com/jerrybendy/url search params-polyfill

And for accessing or modifying query part of the URI you should use "search" property of the window.location.

对于访问或修改URI的查询部分,应该使用windows .location的“search”属性。

Working code example:

工作代码示例:

  var a = document.createElement("a")
  a.href = "http://localhost.com?param1=val&param2=val2&param3=val3#myHashCode";
  var queryParams = new URLSearchParams(a.search)
  queryParams.delete("param2")
  a.search = queryParams.toString();
  console.log(a.href);

#6


1  

Try this:

试试这个:

For reading parameters:

用于读取参数:

const data = ['example.com?var1=value1&var2=value2&var3=value3', 'example.com?a=2&b=2&order_by=data']

const getParameters = url => {
  const parameters = url.split('?')[1],
        regex = /(\w+)=(\w+)/g,
        obj = {}
  let temp
  while (temp = regex.exec(parameters)){
    obj[temp[1]] = decodeURIComponent(temp[2])
  }
  return obj
}

for(let url of data){
  console.log(getParameters(url))
}

For placing only this parameters:

只提供以下参数:

const data = ['example.com?zzz=asd']
const parameters = {a:1, b:2, add: "abs"}

const setParameters = (url, parameters) => {
  const keys = Object.keys(parameters)
  let temp = url.split('?')[0] += '?'
  for (let i = 0; i < keys.length; i++) {
    temp += `${keys[i]}=${parameters[keys[i]]}${i  == keys.length - 1 ? '' : '&'}`
  }
  return temp
}

for (let url of data){
  console.log(setParameters(url, parameters))
}

And finaly for inserting (or replace while exists)

最后用于插入(或在存在时替换)

const data = ['example.com?a=123&b=3&sum=126']
const parameters = {order_by: 'abc', a: 11}
const insertParameters = (url, parameters) => {
  const keys = Object.keys(parameters)
  let result = url
  for (let i = 0; i < keys.length; i++){
    if (result.indexOf(keys[i]) === -1) {
      result += `&${keys[i]}=${encodeURIComponent(parameters[keys[i]])}`
    } else {
      let regex = new RegExp(`${keys[i]}=(\\w+)`)
      result = result.replace(regex, `&${keys[i]}=${encodeURIComponent(parameters[keys[i]])}`)
    }
  }
  return result
}

for (let url of data){
  console.log(insertParameters(url, parameters))
}

Hope this works for you ;) After using function just replace window.location.href

希望这对你有用;使用函数后,只需替换window.location.href

#7


1  

To use Regex pattern, I prefer this one:

要使用Regex模式,我更喜欢以下模式:

var oldUrl = "http://*.com/";
var data_val = "newORDER" ;
var r = /^(.+order_by=).+?(&|$)(.*)$/i ;
var newUrl = "";

var matches = oldUrl.match(r) ;
if(matches===null){
  newUrl = oldUrl + ((oldUrl.indexOf("?")>-1)?"&":"?") + "order_by=" + data_val ;
}else{
  newUrl = match[1]+data_val+match[2]+match[3] ;
}
conole.log(newUrl);

If no order_by exist, matches is null and order_by=.. should come after ? or & (if other parameters exist, new one needs &).

如果没有order_by存在,则匹配为null, order_by=..应该在哪里来?或者&(如果存在其他参数,则需要&)。

If order_by exist, matches has 3 items, see here

如果order_by存在,匹配有3个项目,请参见这里

#8


1  

This small function could help.

这个小函数可以帮上忙。

function changeSearchQueryParameter(oldParameter,newParameter,newValue) {
var parameters = location.search.replace("?", "").split("&").filter(function(el){ return el !== "" });
var out = "";
var count = 0;
if(oldParameter.length>0) {
if(newParameter.length>0 && (newValue.length>0 || newValue>=0)){
	out += "?";
	var params = [];
	parameters.forEach(function(v){
		var vA = v.split("=");
		if(vA[0]==oldParameter) {
			vA[0]=newParameter;
			if((newValue.length>0 || newValue>=0)) {
			vA[1] = newValue;			
			}
		} else {
			count++;
		}
		params.push(vA.join("="));	
	});
	if(count==parameters.length) {
		params.push([newParameter,newValue].join("="));
	}
  params = params.filter(function(el){ return el !== "" });
  if(params.length>1) {
  out += params.join("&");
  } 
  if(params.length==1) {
  out += params[0];
  }	
 }
} else {
if((newParameter.length>0) && (newValue.length>0 || newValue>=0)){
if(location.href.indexOf("?")!==-1) {
var out = "&"+newParameter+"="+newValue;	
} else {
var out = "?"+newParameter+"="+newValue;	
}
}
}
return location.href+out;
}
// if old query parameter is declared but does not exist in url then new parameter and value is simply added if it exists it will be replaced
console.log(changeSearchQueryParameter("ib","idx",5));
// add new parameter and value in url
console.log(changeSearchQueryParameter("","idy",5));
// if no new or old parameter are present url does not change
console.log(changeSearchQueryParameter("","",5));
console.log(changeSearchQueryParameter("","",""));

#9


1  

Maybe you could try tweaking the regular expression to retrieve only the values you're looking for, then add or update them in a helper function, something like this:

也许你可以尝试调整正则表达式,只检索你要查找的值,然后在一个助手函数中添加或更新它们,类似如下:

function paramUpdate(param) {

  var url = window.location.href,
      regExp = new RegExp(param.key + '=([a-z0-9\-\_]+)(?:&)?'),
      existsMatch = url.match(regExp);

  if (!existsMatch) {
      return url + '&' + param.key + '=' + param.value
  }

  var paramToUpdate = existsMatch[0],
      valueToReplace = existsMatch[1],
      updatedParam = paramToUpdate.replace(valueToReplace, param.value);

  return url.replace(paramToUpdate, updatedParam);
}

var new_url = paramUpdate({
    key: 'order_by',
    value: 'id'
});
window.location.href = new_url;

Hope it works well for your needs!

希望它能满足你的需要!

#1


3  

You could use a jQuery plugin to do the all the heavy lifting for you. It will parse the query string, and also reconstruct the updated query string for you. Much less code to deal with.

您可以使用jQuery插件来完成所有繁重的工作。它将解析查询字符串,并为您重构更新后的查询字符串。更少的代码需要处理。

Plugin Download Page
Github Repo

插件下载页面Github Repo

// URL: ?a=2&b=3&order_by=old_data

var order_by = $.query.get('order_by');
//=> old_data

// Conditionally modify parameter value
if (order_by) { 
  order_by = “data”;
}

// Inject modified parameter back into query string
var newUrl = $.query.set(“order_by”, order_by).toString();
//=> ?a=2&b=3&order_by=data

For those using Node.js, there is a package for this available in NPM.

对于那些使用节点。js, NPM中有一个包。

NPM Package
Github Repo

NPM包Github回购

var queryString = require('query-string');
var parsed = queryString.parse('?a=2&b=3&order_by=old_data');  // location.search

// Conditionally modify parameter value
if (parsed.order_by) {
  parsed.order_by = 'data';
}

// Inject modified parameter back into query string
const newQueryString = queryString.stringify(parsed);
//=> a=2&b=3&order_by=data

#2


4  

A good solution ought to handle all of the following:

一个好的解决方案应该处理以下所有问题:

  1. A URL that already has an order_by query parameter, optionally with whitespace before the equals sign. This can be further divided into cases where the order_by appears at the start, middle or end of the query string.
  2. 具有order_by查询参数的URL,可选地在等号之前使用空格。这可以进一步划分为order_by出现在查询字符串的开头、中间或结尾的情况。
  3. A URL that doesn't already have and order_by query parameter but does already have a question mark to delimit the query string.
  4. 一个URL,它没有查询参数order_by,但是已经有一个问号来分隔查询字符串。
  5. A URL that doesn't already have and order_by query parameter and doesn't already have a question mark to delimit the query string.
  6. 一个URL,它没有查询参数order_by,也没有问号来分隔查询字符串。

The following will handle the cases above:

以下将处理上述情况:

  if (/[?&]order_by\s*=/.test(oldUrl)) {
    newUrl = oldUrl.replace(/(?:([?&])order_by\s*=[^?&]*)/, "$1order_by=" + data_val);
  } else if (/\?/.test(oldUrl)) {
    newUrl = oldUrl + "&order_by=" + data_val;
  } else {
    newUrl = oldUrl + "?order_by=" + data_val;
  }

as demonstrated below:

如下证明:

getNewUrl("?a=1&b=2");
getNewUrl("?a=2&b=3&order_by=old_data");
getNewUrl("?a=2&b=3&order_by = old_data&c=4");
getNewUrl("?order_by=old_data&a=2&b=3");
getNewUrl("http://www.*.com");

function getNewUrl(oldUrl) {
  var data_val = "new_data";
  var newUrl;
  if (/[?&]order_by\s*=/.test(oldUrl)) {
    newUrl = oldUrl.replace(/(?:([?&])order_by\s*=[^?&]*)/, "$1order_by=" + data_val);
  } else if (/\?/.test(oldUrl)) {
    newUrl = oldUrl + "&order_by=" + data_val;
  } else {
    newUrl = oldUrl + "?order_by=" + data_val;
  }
  console.log(oldUrl + "\n...becomes...\n" + newUrl);
}  

#3


3  

function addOrReplaceOrderBy(newData) {
  var stringToAdd = "order_by=" + newData;

  if (window.location.search == "")
    return window.location.href + stringToAdd;

  if (window.location.search.indexOf('order_by=') == -1)
    return window.location.href + stringToAdd;

  var newSearchString = "";
  var searchParams = window.location.search.substring(1).split("&");
  for (var i = 0; i < searchParams.length; i++) {
    if (searchParams[i].indexOf('order_by=') > -1) {
      searchParams[i] = "order_by=" + newData;
      break;
    }
  }
  return window.location.href.split("?")[0] + "?" + searchParams.join("&");
}

window.location.href = addOrReplaceOrderBy("new_order_by");

A little long but I think it works as intended.

有一点长,但我认为它是想要的。

#4


1  

something like this?

是这样的吗?

new_url = "";

if(window.location.search && window.location.search.indexOf('order_by=') != -1)
  new_url = window.location.search.replace( /order_by=\w*\d*/, "order_by=" + data_val);
else if(window.location.search)
  new_url = window.location.search + "&order_by=" + data_val;
else
  new_url = window.location.search + "?order_by=" + data_val;

window.location.href = new_url;

#5


1  

You can remove parameter from query string using URLSearchParams https://developer.mozilla.org/ru/docs/Web/API/URLSearchParams?param11=val

您可以使用URLSearchParams从查询字符串中删除参数https://developer.mozilla.org/ru/docs/web/api/urlsearchparams? params?

It is not yet supported by IE and Safari, but you can use it by adding polyfill https://github.com/jerrybendy/url-search-params-polyfill

IE和Safari还不支持它,但是可以通过添加polyfill来使用它:https://github.com/jerrybendy/url search params-polyfill

And for accessing or modifying query part of the URI you should use "search" property of the window.location.

对于访问或修改URI的查询部分,应该使用windows .location的“search”属性。

Working code example:

工作代码示例:

  var a = document.createElement("a")
  a.href = "http://localhost.com?param1=val&param2=val2&param3=val3#myHashCode";
  var queryParams = new URLSearchParams(a.search)
  queryParams.delete("param2")
  a.search = queryParams.toString();
  console.log(a.href);

#6


1  

Try this:

试试这个:

For reading parameters:

用于读取参数:

const data = ['example.com?var1=value1&var2=value2&var3=value3', 'example.com?a=2&b=2&order_by=data']

const getParameters = url => {
  const parameters = url.split('?')[1],
        regex = /(\w+)=(\w+)/g,
        obj = {}
  let temp
  while (temp = regex.exec(parameters)){
    obj[temp[1]] = decodeURIComponent(temp[2])
  }
  return obj
}

for(let url of data){
  console.log(getParameters(url))
}

For placing only this parameters:

只提供以下参数:

const data = ['example.com?zzz=asd']
const parameters = {a:1, b:2, add: "abs"}

const setParameters = (url, parameters) => {
  const keys = Object.keys(parameters)
  let temp = url.split('?')[0] += '?'
  for (let i = 0; i < keys.length; i++) {
    temp += `${keys[i]}=${parameters[keys[i]]}${i  == keys.length - 1 ? '' : '&'}`
  }
  return temp
}

for (let url of data){
  console.log(setParameters(url, parameters))
}

And finaly for inserting (or replace while exists)

最后用于插入(或在存在时替换)

const data = ['example.com?a=123&b=3&sum=126']
const parameters = {order_by: 'abc', a: 11}
const insertParameters = (url, parameters) => {
  const keys = Object.keys(parameters)
  let result = url
  for (let i = 0; i < keys.length; i++){
    if (result.indexOf(keys[i]) === -1) {
      result += `&${keys[i]}=${encodeURIComponent(parameters[keys[i]])}`
    } else {
      let regex = new RegExp(`${keys[i]}=(\\w+)`)
      result = result.replace(regex, `&${keys[i]}=${encodeURIComponent(parameters[keys[i]])}`)
    }
  }
  return result
}

for (let url of data){
  console.log(insertParameters(url, parameters))
}

Hope this works for you ;) After using function just replace window.location.href

希望这对你有用;使用函数后,只需替换window.location.href

#7


1  

To use Regex pattern, I prefer this one:

要使用Regex模式,我更喜欢以下模式:

var oldUrl = "http://*.com/";
var data_val = "newORDER" ;
var r = /^(.+order_by=).+?(&|$)(.*)$/i ;
var newUrl = "";

var matches = oldUrl.match(r) ;
if(matches===null){
  newUrl = oldUrl + ((oldUrl.indexOf("?")>-1)?"&":"?") + "order_by=" + data_val ;
}else{
  newUrl = match[1]+data_val+match[2]+match[3] ;
}
conole.log(newUrl);

If no order_by exist, matches is null and order_by=.. should come after ? or & (if other parameters exist, new one needs &).

如果没有order_by存在,则匹配为null, order_by=..应该在哪里来?或者&(如果存在其他参数,则需要&)。

If order_by exist, matches has 3 items, see here

如果order_by存在,匹配有3个项目,请参见这里

#8


1  

This small function could help.

这个小函数可以帮上忙。

function changeSearchQueryParameter(oldParameter,newParameter,newValue) {
var parameters = location.search.replace("?", "").split("&").filter(function(el){ return el !== "" });
var out = "";
var count = 0;
if(oldParameter.length>0) {
if(newParameter.length>0 && (newValue.length>0 || newValue>=0)){
	out += "?";
	var params = [];
	parameters.forEach(function(v){
		var vA = v.split("=");
		if(vA[0]==oldParameter) {
			vA[0]=newParameter;
			if((newValue.length>0 || newValue>=0)) {
			vA[1] = newValue;			
			}
		} else {
			count++;
		}
		params.push(vA.join("="));	
	});
	if(count==parameters.length) {
		params.push([newParameter,newValue].join("="));
	}
  params = params.filter(function(el){ return el !== "" });
  if(params.length>1) {
  out += params.join("&");
  } 
  if(params.length==1) {
  out += params[0];
  }	
 }
} else {
if((newParameter.length>0) && (newValue.length>0 || newValue>=0)){
if(location.href.indexOf("?")!==-1) {
var out = "&"+newParameter+"="+newValue;	
} else {
var out = "?"+newParameter+"="+newValue;	
}
}
}
return location.href+out;
}
// if old query parameter is declared but does not exist in url then new parameter and value is simply added if it exists it will be replaced
console.log(changeSearchQueryParameter("ib","idx",5));
// add new parameter and value in url
console.log(changeSearchQueryParameter("","idy",5));
// if no new or old parameter are present url does not change
console.log(changeSearchQueryParameter("","",5));
console.log(changeSearchQueryParameter("","",""));

#9


1  

Maybe you could try tweaking the regular expression to retrieve only the values you're looking for, then add or update them in a helper function, something like this:

也许你可以尝试调整正则表达式,只检索你要查找的值,然后在一个助手函数中添加或更新它们,类似如下:

function paramUpdate(param) {

  var url = window.location.href,
      regExp = new RegExp(param.key + '=([a-z0-9\-\_]+)(?:&)?'),
      existsMatch = url.match(regExp);

  if (!existsMatch) {
      return url + '&' + param.key + '=' + param.value
  }

  var paramToUpdate = existsMatch[0],
      valueToReplace = existsMatch[1],
      updatedParam = paramToUpdate.replace(valueToReplace, param.value);

  return url.replace(paramToUpdate, updatedParam);
}

var new_url = paramUpdate({
    key: 'order_by',
    value: 'id'
});
window.location.href = new_url;

Hope it works well for your needs!

希望它能满足你的需要!