用javascript我怎么能添加一个查询字符串参数的url,如果不存在或如果它存在,更新当前值?我使用jquery为我的客户端开发。


当前回答

这个答案只是ellemayo的答案的一个小调整。它将自动更新URL,而不只是返回更新后的字符串。

function _updateQueryString(key, value, url) {
    if (!url) url = window.location.href;

    let updated = ''
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
        hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null) {
            updated = url.replace(re, '$1' + key + "=" + value + '$2$3');
        } 
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                url += '#' + hash[1];
            }
            updated = url;
        }
    }
    else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                url += '#' + hash[1];
            }
            updated = url;
        }
        else {
            updated = url;
        }
    }

    window.history.replaceState({ path: updated }, '', updated);
}

其他回答

感谢现代javascript, node.js和浏览器的支持,我们可以摆脱第三方库的漩涡(jquery, query-string等)和DRY自己。

下面是javascript(node.js)和typescript版本的函数,用于添加或更新给定url的查询参数:

Javascript

const getUriWithParam = (baseUrl, params) => { const Url = new URL(baseUrl); const urlParams = new URLSearchParams(Url.search); for (const key in params) { if (params[key] !== undefined) { urlParams.set(key, params[key]); } } Url.search = urlParams.toString(); return Url.toString(); }; console.info('expected: https://example.com/?foo=bar'); console.log(getUriWithParam("https://example.com", {foo: "bar"})); console.info('expected: https://example.com/slug?foo=bar#hash'); console.log(getUriWithParam("https://example.com/slug#hash", {foo: "bar"})); console.info('expected: https://example.com/?bar=baz&foo=bar'); console.log(getUriWithParam("https://example.com?bar=baz", {foo: "bar"})); console.info('expected: https://example.com/?foo=baz&bar=baz'); console.log(getUriWithParam("https://example.com?foo=bar&bar=baz", {foo: "baz"}));

打印稿


const getUriWithParam = (
  baseUrl: string,
  params: Record<string, any>
): string => {
  const Url = new URL(baseUrl);
  const urlParams: URLSearchParams = new URLSearchParams(Url.search);
  for (const key in params) {
    if (params[key] !== undefined) {
      urlParams.set(key, params[key]);
    }
  }
  Url.search = urlParams.toString();
  return Url.toString();
};

对于React Native

URL在React Native中没有实现。所以你必须事先安装react-native-url-polyfill。

对于对象参数

请看这个答案中的第二个解决方案

下面是我对此略有不同的方法,作为练习写的

function addOrChangeParameters( url, params )
{
  let splitParams = {};
  let splitPath = (/(.*)[?](.*)/).exec(url);
  if ( splitPath && splitPath[2] )
    splitPath[2].split("&").forEach( k => { let d = k.split("="); splitParams[d[0]] = d[1]; } );
  let newParams = Object.assign( splitParams, params );
  let finalParams = Object.keys(newParams).map( (a) => a+"="+newParams[a] ).join("&");
  return splitPath ? (splitPath[1] + "?" + finalParams) : (url + "?" + finalParams);
}

用法:

const url = "http://testing.com/path?empty&value1=test&id=3";

addOrChangeParameters( url, {value1:1, empty:"empty", new:0} )

"http://testing.com/path?empty=empty&value1=1&id=3&new=0"

给出Gal和tradyblix建议的修改window.location.search的代码示例:

var qs = window.location.search || "?";
var param = key + "=" + value; // remember to URI encode your parameters
if (qs.length > 1) {
    // more than just the question mark, so append with ampersand
    qs = qs + "&";
}
qs = qs + param;
window.location.search = qs;

一种不使用正则表达式的不同方法。支持url末尾的“散列”锚以及多个问号字符(?)。应该比正则表达式方法略快。

function setUrlParameter(url, key, value) {
  var parts = url.split("#", 2), anchor = parts.length > 1 ? "#" + parts[1] : '';
  var query = (url = parts[0]).split("?", 2);
  if (query.length === 1) 
    return url + "?" + key + "=" + value + anchor;

  for (var params = query[query.length - 1].split("&"), i = 0; i < params.length; i++)
    if (params[i].toLowerCase().startsWith(key.toLowerCase() + "="))
      return params[i] = key + "=" + value, query[query.length - 1] = params.join("&"), query.join("?") + anchor;

  return url + "&" + key + "=" + value + anchor
}

使用此函数可以添加、删除和修改URL中的查询字符串参数

/**
@param String url
@param object param {key: value} query parameter
*/
function modifyURLQuery(url, param){
    var value = {};

    var query = String(url).split('?');

    if (query[1]) {
        var part = query[1].split('&');

        for (i = 0; i < part.length; i++) {
            var data = part[i].split('=');

            if (data[0] && data[1]) {
                value[data[0]] = data[1];
            }
        }
    }

    value = $.extend(value, param);

    // Remove empty value
    for (i in value){
        if(!value[i]){
            delete value[i];
        }
    }

    // Return url with modified parameter
    if(value){
        return query[0] + '?' + $.param(value);
    } else {
        return query[0];
    }
}

添加新的和修改现有参数的url

var new_url = modifyURLQuery("http://google.com?foo=34", {foo: 50, bar: 45});
// Result: http://google.com?foo=50&bar=45

删除现有的

var new_url = modifyURLQuery("http://google.com?foo=50&bar=45", {bar: null});
// Result: http://google.com?foo=50