1

jQuery has a param() function, I'm looking for similar functionality. I need to return a url in my object. For example:

url: function() {
  return this.baseUrl + '?' + $.param({page: this.page, perPage: this.perPage});
},

this will return a url in the form of example.com/?page=1&perPage=5 or something similar. How can I form the url example.com/page/1/perpage/5?

Matthew
  • 15,282
  • 27
  • 88
  • 123

3 Answers3

2

You can create your own function:

function build(base, params) {
    for(var k in params) {
        if(params.hasOwnProperty(k)) {
            base += '/' + k + '/' + params[k];
        }
    }
    return base;
}

The only problem is that the order of the parameters is not guaranteed (which is not a problem for query strings but might be for this kind of URLs). You might also want to add a check if base already ends with a slash or not.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

Just an idea :)

'example.com/?page=1&perPage=5'.replace(/[&=]/g,'/').replace('?','')
 .toLowerCase();
Gary Green
  • 22,045
  • 6
  • 49
  • 75
  • +1 interesting idea. The only problem could be if a question mark is part of a parameter value. – Felix Kling Apr 27 '11 at 20:41
  • Absolutely, but that's the beauty of still using `.param` -- as `?` is a reserved character in a URL it will be escaped by jquery: `document.write($.param({'blah': 'lol?hi' }));` – Gary Green Apr 27 '11 at 20:50
  • Interesting. Because actually inside the query string, `?` does not have to be escaped (afaik). But nice to know that jQuery does escape it. Thanks :) – Felix Kling Apr 27 '11 at 20:55
  • @Felix Indeed, URLs are very forgiving with reserved characters, but jQuery correctly follows the books here; Page 7, 2.2. Reserved Characters: http://www.ietf.org/rfc/rfc2396.txt – Gary Green Apr 28 '11 at 07:19
0

tack this on the end:

replace(/[&=]/g,'/').replace('?','')

like so:

url: function() {
  return (this.baseUrl + '?' + $.param({page: this.page, perPage: this.perPage})).replace(/[&=]/g,'/').replace('?','');
},

edited to point out in re to Felix Kling's concern about ?'s: This will only remove the FIRST ? leaving any other ?'s that are part of the query string INTACT. Perfectly safe to use.

ampersand
  • 4,264
  • 2
  • 24
  • 32
  • Right. I forgot that JavaScript is acting (for me) strange, concerning replacing characters... thanks for pointing that out again! – Felix Kling Apr 27 '11 at 23:48