JavaScript函数替换URL参数无法正常工作

时间:2019-02-22 05:37:15

标签: javascript

我具有替换分页按钮上的URL参数的功能。如果我的URLhttps://example.com/,我得到正确的URL,但是如果我的URL已经有一些参数,例如小提琴,仅最后一个参数被替换。在这种情况下,我也如何获得正确的URL

var sURL = "https://example.com/?&page=2&order=price&direction=ASC";
//var sURL = "https://example.com/"; 
function insertParam(no, ord, dir) {
  var page = "page";
  var order = "order";
  var direction = "direction";
  page = encodeURI(page);
  order = encodeURI(order);
  direction = encodeURI(direction);

  no = encodeURI(no);
  ord = encodeURI(ord);
  dir = encodeURI(dir);

  var kvp = sURL.substr(1).split('&');

  var i = kvp.length;
  var x;

  while (i--) {
    x = kvp[i].split('=');

    if (x[0] === page) {
      x[1] = no;
      kvp[i] = x.join('=');
      break;
    }
    if (x[0] === order) {
      x[1] = ord;
      kvp[i] = x.join('=');
      break;
    }
    if (x[0] === direction) {
      x[1] = dir;
      kvp[i] = x.join('=');
      break;
    }
  }

  if (i < 0) {
    kvp[kvp.length] = [page, no].join('=');
    kvp[kvp.length] = [order, ord].join('=');
    kvp[kvp.length] = [direction, dir].join('=');
  }
	sURL = kvp.join('&');
  alert(sURL);
}

insertParam(3, 'my_id', 'DESC');

3 个答案:

答案 0 :(得分:2)

我认为您需要遵循另一种方法来满足您的要求,希望它会对您有所帮助。

function insertParam(endpoint, no, ord, dir){
const sURL = endpoint + "?&page=" + no + "&order=" + ord + "&direction=" + dir;
return sURL
}

const url = insertParam("https://example.com/", 2, 123, "ASC");
// https://example.com/?&page=2&order=123&direction=ASC

答案 1 :(得分:1)

检出URL类。它可以帮助您处理所有与URL相关的怪异事物。这是您使用它的功能:

var sURL = "https://example.com/?&page=2&order=price&direction=ASC";

function insertParam(page = 2, order = "price", direction = "ASC") {
  const u = new URL(sURL);
  u.searchParams.set("page", page);
  u.searchParams.set("order", order);
  u.searchParams.set("direction", direction);
  return u.toString();
}

console.log(insertParam(1, "foo", "DESC"));

console.log(insertParam(5));
.as-console-wrapper{top:0;max-height:100%!important}

或更通用的解决方案

const urlBuilder = (url, defaults = {}) => (props) => {
  const u = new URL(url);
  for(let [key, value] of Object.entries(props ? { ...defaults, ...props } : defaults)) {
    u.searchParams.set(key, value);
  }
  return u.toString();
}

// create a function that will build the urls for a particular page/route
const routeFoo = urlBuilder("https://example.com", {
  page: 2,
  order: "price",
  direction: "ASC"
});

console.log(routeFoo({
  page: 5
}));

console.log(routeFoo({
  page: 1,
  direction: "DESC",
  foo: 42,
  additional: "properties",
  "also deals with weird/malicious stuff": "like special chars like /#%? & more"
}));

// or just the defaults
console.log(routeFoo());
.as-console-wrapper{top:0;max-height:100%!important}

答案 2 :(得分:0)

尝试使用 newurl = location.search.replace(/^.*?\=/,``); newurl = newurl.replace(“ +”,“”);