Freeman
Freeman

Reputation: 3

How to replace query string value in the url using Jquery

I want to change the url query string value from an url. For example: I have this url: www.example.com/site-post/234-1993/ So let's say that 234 is the person_id and 1993 person_year. without rewrite rule the url looks like this: www.example.com/site-post/?person_id=234&person_year=1993

When i press on a button I want to change the value 234 and 1993.

I have a function which works for unfriendly url.

function update_permalink(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;
    }
}

If I call this function it will change my url www.example.com/site-post/234-1993/ to www.example.com/site-post/234-1993/?person_id=234&person_year=1993

Is there someone who knows how can I change the url without append current url with the query string, only changing the values ?

Upvotes: 0

Views: 158

Answers (2)

Bhupendra Tiwari
Bhupendra Tiwari

Reputation: 59

Place this code in your function and check.

if (window.location.href.indexOf("234") > 0){
   var newUrl = window.location.href.replace("234-1993/", "?person_id=234&person_year=1993");
   window.history.replaceState({}, '', newUrl);
}

Upvotes: 1

Alireza
Alireza

Reputation: 161

I'm not really sure why you want to do this, but this code should work:

function update_permalink(uri, param1, param2) {
  var re = uri.match(/([^\?]*)\/site-post\/(\d*)-(\d*)\//); 
  if (uri.match(/([^\?]*)\/site-post\/(\d*)-(\d*)\//)){
    uri = uri.replace(re[2],param1); 
    uri = uri.replace(re[3],param2); 
    return uri;
  }
}

then use that like:

update_permalink("www.example.com/site-post/234-1993/",112,113);

result:

www.example.com/site-post/112-113/

Upvotes: 0

Related Questions