-1

Example:

I have string like this : http://example.com/path/?value1=123&value2=334&value3=x2y&value4=2bx

How can I exactly replace string above with exact value I want.

Such as, I want to replace to change value2=334 to value2=b2y

I mean that the current value of value2 will be replaced with b2y.  

I use Jquery only. Thank for your support.

Hai Tien
  • 2,929
  • 7
  • 36
  • 55

1 Answers1

1

1- for getting query param from any url

function getQueryVariable(url, variable) {
     var query = url.substring(1);
     var vars = query.split('&');
     for (var i=0; i<vars.length; i++) {
          var pair = vars[i].split('=');
          if (pair[0] == variable) {
            return pair[1];
          }
     }

     return false;
  }

Example var url = 'http://www.example.com/hello.png?w=100&h=101&bg=white';

 var w = getQueryVariable(url, 'w');//100
  var h = getQueryVariable(url, 'h');//101
  var bg = getQueryVariable(url, 'bg');//white

Credit: https://stackoverflow.com/a/9622263/8621306

2- Set the Query Param of a url

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

Credit https://stackoverflow.com/a/6021027/8621306

Santosh Kumar
  • 1,756
  • 15
  • 24