如何在这个网址上附加一个参数?

时间:2017-03-09 07:24:52

标签: javascript jquery

我有一个脚本,当我点击一个按钮时,会在URL的末尾添加一个参数。它适用于“干净”的URL,但在少数情况下,我有一个不同的URL,使脚本将我发送到我的主页。如何调整它以使用下面的字符串?

  

/ M 4 N searchtrack =过滤+选项&安培; manid = 24&安培; SEID =电子零售商的产品&安培; CNT = 10安培; cat1id = 14&安培; VIEWMODE = 1&安培; _ = 1489044215226

$(function getParameterByName(name) {
  if (window.location.href.indexOf("param=largegrid") > -1) {
    $("body").addClass("largegrid");
  } else if (window.location.href.indexOf("param=grid") > -1) {
    $("body").addClass("gridview");
  } else {
    $("body").addClass("listview focuslist");
  }

  $('.click10').on('click', function() {
    console.log("Clicked");
    var baseUrl = window.location.href.split("?")[0];
    var fss = getParametersByName("fss");
    var params = getParametersByName("param");

    if (params == "largegrid")
      param = "largegrid";
    else 
      param = "largegrid";

    var newUrl = baseUrl + "?param=" + param;
    if ((fss).length > 0) 
      newUrl = newUrl + "&fss=" + fss;

    window.location.href = newUrl;

    function getParametersByName(name) {
      name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
      var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
      return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
  });
});

2 个答案:

答案 0 :(得分:0)

合并网址

中的参数
function merge(url, params,rest) {
    var params=typeof params=='object'?params:Object.defineProperty({},params,{enumerable:true,value:rest}),
    parts = url.split(/\?/), host = parts.shift(), query = parts.join(''),
        regSymbols = /[.?*+^$[\]\\(){}|-]/g;

    for (var name in params) {
        var value = encodeURIComponent(params[name]),
            rawName = name.replace(regSymbols, "\\$&"),
            name = encodeURIComponent(name);

        var ret = query.replace(new RegExp('((?:^|&)(?:' + (name + '|' + rawName) + ')=)([\\w%]+)'), "$1" + value);

        query = ret != query ? ret : [query, name + "=" + value].join(query ? '&' : '');
    }

    return query ? host + '?' + query : host;
}

实例/测试

describe('merge parameter', () => {

    it('starts with ?', () => {
        expect(merge('www.example.com?foo=bar', 'foo', 'baz'))
            .toEqual('www.example.com?foo=baz');
    });

    it('merge multi-params', () => {
        expect(merge('www.example.com', {foo: 'bar', fuzz: 'buzz'}))
            .toEqual('www.example.com?foo=bar&fuzz=buzz');
    });

    it('return URL be consistent when merge url with empty params if url with no params', () => {
        expect(merge('www.example.com', {}))
            .toEqual('www.example.com');
    });

    it('merge param with brackets', () => {
        expect(merge('www.example.com?[foo]=bar', '[foo]', 'baz'))
            .toEqual('www.example.com?[foo]=baz');
    });

    it('starts with &', () => {
        expect(merge('www.example.com?id=1&foo=bar', 'foo', 'baz'))
            .toEqual('www.example.com?id=1&foo=baz');
    });

    it('no params', () => {
        expect(merge('www.example.com', 'foo', 'baz'))
            .toEqual('www.example.com?foo=baz');
    });

    it('add param if param is missing', () => {
        expect(merge('www.example.com?id=1', 'foo', 'baz'))
            .toEqual('www.example.com?id=1&foo=baz');
    });

    it('merge encoded param value', () => {
        expect(merge('www.example.com?foo=bar%20baz', 'foo', 'baz'))
            .toEqual('www.example.com?foo=baz');
    });

    it('merge encoded param name', () => {
        expect(merge('www.example.com?foo%20value=bar', 'foo value', 'baz'))
            .toEqual('www.example.com?foo%20value=baz');
    });

    it('merge with encoded param', () => {
        expect(merge('www.example.com?foo=bar', 'foo', 'bar baz'))
            .toEqual('www.example.com?foo=bar%20baz');
    });

    it('add encoded param', () => {
        expect(merge('www.example.com', 'foo', 'bar baz'))
            .toEqual('www.example.com?foo=bar%20baz');
    });
});

演示



function merge(url, params,rest) {
    var params=typeof params=='object'?params:Object.defineProperty({},params,{enumerable:true,value:rest}),
    parts = url.split(/\?/), host = parts.shift(), query = parts.join(''),
        regSymbols = /[.?*+^$[\]\\(){}|-]/g;

    for (var name in params) {
        var value = encodeURIComponent(params[name]),
            rawName = name.replace(regSymbols, "\\$&"),
            name = encodeURIComponent(name);

        var ret = query.replace(new RegExp('((?:^|&)(?:' + (name + '|' + rawName) + ')=)([\\w%]+)'), "$1" + value);

        query = ret != query ? ret : [query, name + "=" + value].join(query ? '&' : '');
    }

    return query ? host + '?' + query : host;
}


function play(){
  function val(id){return document.getElementById(id).value;}
  console.log(merge(val('url'),val('name'),val('value')));
}

<h1>Merge URL parameters</h1>
URL:<input id="url" value="http://www.example.com?[foo]=bar&t=123" style="width:280px;"><button onclick="play()">Merge</button><br>
Name:<input id="name" value="[foo]" style="width:100px;">
Value:<input id="value" value="baz" style="width:100px;">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var str = '/m4n?searchtrack=Filter+options&manid=24&seid=etailer-products&cnt=10&cat1id=14&viewMode=1&_=1489044215226';
/**
 * parametize takes an url and a list of additional parameters
 *
 * @param {string} url
 * @param {[string, string][]} [parameters=[]]
 * @returns {string}
 */
function parametize(url, parameters) {
  if (parameters === void 0) {
    parameters = [];
  }
  //If no parameters, return
  if (url.indexOf('?') < 0) {
    return '';
  }
  //Filter to parameter part
  var params = url.split("?")[1].split("&").map(function(param) {
    return param.split("=");
  });
  for (var parametersIndex = 0; parametersIndex < parameters.length; parametersIndex++) {
    var parameter = parameters[parametersIndex];
    var index = params.map(function(a) {
      return a[0].toString();
    }).indexOf(parameter[0].toString());
    if (index >= 0) {
      params[index] = parameter;
    } else {
      params.push(parameter);
    }
  }
  return url.split("?")[0] + '?' + params.map(function(a) {
    return a.join("=");
  }).join("&");
}
console.log(parametize(str, [
  ['_', 'BATMAN']
]));
console.log(parametize(str, [
  ['__', 'BATMAN']
]));
console.log(parametize(str, [
  ['superhero1', 'BATMAN'],
  ['superhero0', 'WONDERWOMAN'],
  ['superhero2', 'SUPERMAN']
]));