32

I have an example URL like:

http://domain.com/Documents/?page=1&name=Dave&date=2011-01-01

The query string contains the current page number and two additional filters (name and date).

Using the following URL parser: https://github.com/allmarkedup/purl I am able to access certain parts of the URL such as just the page number.

I'm trying to create a way for a user to be able to type a number into a textbox and then load that page number whilst keeping all the other query strings intact.

$(document).ready(function () {

        $('.pageNum').live('keyup', function (e) {
            e.preventDefault();
            if (e.which == 13) {

                var currentUrl = window.location.href;

                var parsedUrl = $.url(currentUrl);

                var currentPageNum = parsedUrl.param('page');

                var newPageNum = $(this).val();

                var newUrl = //

                window.location.href = newUrl;

            }
        });

    });

So when a user hits return on the pageNum textbox, it will get the current page url, parse it, then find out the current page number and then I need a way to replace the value of the page number with the new value in the textbox to create a new url, and then finally refresh the page using this new url.

Is it possible to change the param value and then add it back in?

Note: The additional parameters could be anything, so I can't manually add them onto the pathname with the new page number!

Cameron
  • 27,963
  • 100
  • 281
  • 483

2 Answers2

58

If you only need to modify the page num you can replace it:

var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);
Kaizo
  • 4,155
  • 2
  • 23
  • 26
  • 18
    Actually... There is need for complication in many cases. Your replace statement will replace `mypage` value in `mypage=1&page=1`. – Nux May 04 '15 at 10:47
  • 3
    @Nux You are right, but the question was specific and the solution was not intended to be general. If you want it more general it could be two replaces instead of one: "?page=1" and "&page=1". – Kaizo May 05 '15 at 10:31
  • 1
    this does not work – tdbeckett Sep 12 '19 at 21:49
33

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);
Andreas
  • 21,535
  • 7
  • 47
  • 56
  • @kev, your message is misleading. I tested `purl` and it works fine. The URI spec, [RFC 3986](https://tools.ietf.org/html/rfc3986#section-3.4), was written in 2005 and I don't think this simple parsing needs a ton of maintenance. If you need more, clone the repo and add on. – vinnyjames Mar 21 '19 at 22:12