1

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=.

Working Case:

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

Non-Working Case:

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?

2 Answers 2

4

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: '' }
Sign up to request clarification or add additional context in comments.

1 Comment

Much better than what I was doing before. I'm pretty sure I'd tried this and it had failed for some reason, probably me not removing the search from the parsed URL. Where I had two problems, I now have none. Thanks!
1

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 ?:.

1 Comment

It should be noted I have about zero applicable regex experience, other than stealing things from the internet. Thanks for the help though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.