Node.js url.parse result back to string
The other answer is good, but you could also do something like this. The querystring
module is used to work with query strings.
var querystring = require('querystring');
var qs = querystring.parse(parts.query);
qs.page = 25;
parts.search = '?' + querystring.stringify(qs);
var newUrl = url.format(parts);
Seems to me like it's a bug in node. You might try
// in requires
var url = require('url');
var qs = require('querystring');
// later
var parts = url.parse(req.url, true);
parts.query['page'] = 25;
parts.query = qs.stringify(parts.query);
console.log("Link: ", url.format(parts));
If you look at the latest documentation, you can see that url.format
behaves in the following way:
search
will be used in place ofquery
query
(object; see querystring) will only be used ifsearch
is absent.
And when you modify query
, search
remains unchanged and it uses it. So to force it to use query
, simply remove search
from the object:
var url = require("url");
var parts = url.parse("http://test.com?page=25&foo=bar", true);
parts.query.page++;
delete parts.search;
console.log(url.format(parts)); //http://test.com/?page=26&foo=bar
Make sure you're always reading the latest version of the documentation, this will save you a lot of trouble.