如何添加或更新查询字符串参数? [英] How can I add or update a query string parameter?

查看:175
本文介绍了如何添加或更新查询字符串参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用javascript如何在网址中添加查询字符串参数(如果不存在)或是否存在,更新当前值?我正在使用jquery进行客户端开发。

With javascript how can I add a query string parameter to the url if not present or if it present, update the current value? I am using jquery for my client side development.

推荐答案

我编写了以下函数来完成我想要实现的目标:

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;
  }
}

这篇关于如何添加或更新查询字符串参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆