0

I want to change the parameters of a url and put the changed url into a variable, but it is undefined. Is there any way to put the url with the parameter changed into a variable? I have tried the following.

const url = new URL(window.location.href);
const params = new URLSearchParams(url.search.slice(1));

const aUrl = params.set('link','abc');
uasidniue
  • 11
  • 1

1 Answers1

0

I use this function.

function UpdateQueryString(key, value, url) {
  if (!url) url = window.location.href;
  var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
    hash;

  if (re.test(url)) {
    if (typeof value !== 'undefined' && value !== null) {
      return 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];
      }
      return 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];
      }
      return url;
    } else {
      return url;
    }
  }
}

var url = window.location.href + "?name=avi";
console.log(url)
var new_url = UpdateQueryString("name", "value", url);
console.log(new_url)
// window.location.replace(new_url);

Now if you want also to work with arrays, know that this isn't defined well. Three possible ways to send multi-value fields or arrays would be:

  • ?cars[]=Saab&cars[]=Audi (Best way- PHP reads this into an array)
  • ?cars=Saab&cars=Audi (Bad way- PHP will only register last value)
  • ?cars=Saab,Audi (Haven't tried this)

So use at your own risk.

Anyway, these 2 functions should help: queryStringToJSON and it's opposite fromObjectToQueryString

function queryStringToJSON(qs) {
  qs = qs || location.search.slice(1);

  var pairs = qs.split('&');
  var result = {};
  pairs.forEach(function(p) {
    var pair = p.split('=');
    var key = pair[0];
    var value = decodeURIComponent(pair[1] || '');

    if (result[key]) {
      if (Object.prototype.toString.call(result[key]) === '[object Array]') {
        result[key].push(value);
      } else {
        result[key] = [result[key], value];
      }
    } else {
      result[key] = value;
    }
  });

  return result;
};

// now backwards:

var isObj = function(a) {
  if ((!!a) && (a.constructor === Object)) {
    return true;
  }
  return false;
};
var _st = function(z, g) {
  return "" + (g != "" ? "[" : "") + z + (g != "" ? "]" : "");
};

function fromObjectToQueryString(params, skipobjects, prefix) {
  if (skipobjects === void 0) {
    skipobjects = false;
  }
  if (prefix === void 0) {
    prefix = "";
  }
  var result = "";
  if (typeof(params) != "object") {
    return prefix + "=" + encodeURIComponent(params) + "&";
  }
  for (var param in params) {
    var c = "" + prefix + _st(param, prefix);
    if (isObj(params[param]) && !skipobjects) {
      result += fromObjectToQueryString(params[param], false, "" + c);
    } else if (Array.isArray(params[param]) && !skipobjects) {
      params[param].forEach(function(item, ind) {
        result += fromObject(item, false, c + "[" + ind + "]");
      });
    } else {
      result += c + "=" + encodeURIComponent(params[param]) + "&";
    }
  }
  return result;
};


var qs = "names=avi&names=ben&names=cat&value=12";
console.log(qs);
var obj = queryStringToJSON(qs)
console.log(obj)
obj["names"][2] = "carter";
console.log(fromObject(obj))

Sources:

See also:

IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • Thank you very much. This worked perfectly. Is it possible to specify a specific parameter to change if there is more than one of the same parameter in this code? Example: example.com?link=a&link=b → example.com?link=a&link=abc – uasidniue Jul 06 '22 at 01:23
  • Thank you so much. You have helped me to solve the problem. – uasidniue Jul 08 '22 at 01:23