Reputation: 16456
I had a regex function that I thought worked for removing the page variable in a querystring. Right now it works fine if the variable isn't first, however if the variable is the first variable, it doesn't catch ?search=.
http://blahblah.com/stuff/pages/things?search=somethingURIEncoded&page=2
turns into
console.log( req.url.replace(/&page(\=[^&]*)?(?=&|$)|^page(\=[^&]*)?(&|$)/, '') )
http://blahblah.com/stuff/pages/things?search=somethingURIEncoded
http://blahblah.com/stuff/pages/things?page=2&search=somethingURIEncoded
turns into
console.log( req.url.replace(/&page(\=[^&]*)?(?=&|$)|^page(\=[^&]*)?(&|$)/, '') )
http://blahblah.com/stuff/pages/things?page=2&search=somethingURIEncoded
Anyone know how to fix this regex I'm using?
Upvotes: 1
Views: 162
Reputation: 276436
If you want to parse a whole url, node.js has a built in url
module.
It has a parse method that seems to do what you need:
url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
This question answers how to build it back into a URL if you'd like, and shows a usage example.
You also have a built-in querystring
module.
You can use querystring.parse
querystring.parse('foo=bar&baz=qux&baz=quux&corge')
// returns
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
Upvotes: 4
Reputation: 191779
Instead of ^page
it should be \?page
, but of course you would have to replace the ?
back. You can capture it and make all of the other groupings non-capture with ?:
.
Upvotes: 1