Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

javascript - 如何添加或更新查询字符串参数?(How can I add or update a query string parameter?)

With javascript how can I add a query string parameter to the url if not present or if it present, update the current value?

(使用javascript,如何将查询字符串参数添加到url(如果不存在)或如果存在,则更新当前值?)

I am using jquery for my client side development.

(我正在使用jquery进行客户端开发。)

  ask by amateur translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I wrote the following function which accomplishes what I want to achieve:

(我编写了以下函数来实现我想要实现的功能:)

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...