0

I have a url:

www.domain.com/bla/

and button in result page:

show 10, 20, 50 per page

and pagination:

1, 2, 3, 5.. 

but once I have clicked 10, url becomes www.domain.com/bla/?show=10, and then if i click page 2, show=10 is disappearing and becoming www.domain.com/bla/?page=2

I have several solution in js, but what is the best and professional way of doing this?

my code:

var show= $('#show').val();
var url = String(window.location);
if(url.indexOf("page") !== -1){
      var newurl = url +'&show='+show;
      $('.entries').html(' ').load(newurl, function(){
              $(this).fadeIn();
       });
}else{
      var newurl = url +'?show='+sortterm;
      $('.entries').html(' ').load(newurl, function(){
              $(this).fadeIn();
       });
}
doniyor
  • 36,596
  • 57
  • 175
  • 260

1 Answers1

2

Just use JS replace method

var yourURL = "www.domain.com/bla/?page=10";
var newURL = yourURL.replace("?page", "?show"); //returns www.domain.com/bla/?show=10

Updates:

With help of this answer, I learned to use the following prototype to insert a string at a specific index.

String.prototype.splice = function( idx, rem, s ) {
    return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
};

Using this I have modified the code

var url = "www.domain.com/bla/?page=10";
var insertIndex = url.indexOf('page=10'); //get the index of page
var final = url.splice( insertIndex, 0, "page=2&" ).replace('&page', '&show');

console.log(final); //returns www.domain.com/bla/?page=2&show=10

JSFiddle

Community
  • 1
  • 1
Praveen
  • 55,303
  • 33
  • 133
  • 164