0

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 ?

2
  • jQuery is javascript Commented Mar 25, 2017 at 9:39
  • 1
    Not an answer to your question, but you are 100% sure you know what you are doing here? You know that this may be better done using server-side URL rewrites? Commented Mar 25, 2017 at 9:41

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.