Jonathan.Brink
Jonathan.Brink

Reputation: 25383

Remove url param with regex

Given a url, I'm trying to remove a particular url parameter.

For example, if I had:

http://example.com?foo=bar&baz=boo

And I wanted to get rid of foo=bar and be left with:

http://example.com?baz=boo

Or if I wanted to remove baz=boo I would be left with:

http://example.com?foo=bar

I'm trying to use a regular expression along with the string's replace function.

Here's what I have:

// s is "foo"
new RegExp("([&?]+)" + s + "=.*&")

It's not working for the case of:

http://example.com?foo=bar

Because it's not matching the &, but I can't figure out how to craft the regex to handle both of these situations.

jsBin

Upvotes: 1

Views: 97

Answers (3)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Working fiddle

I think that what you looking for, using group to deal with the both cases with & and without it :

"([&?]+)" + s + "=(.*&|.*$)?"

Edit : Update fiddle

You could add ? if you want to stop on the first occurance of & (if exist) :

"([&?]+)" + s + "=(.*?&|.*$)?"
_____________________^

Hope this helps.

Upvotes: 1

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

str = str.replace(/(?:\?|&)(foo[^=]*=[^&]+)(?:&|$)/,'');

DEMO

Upvotes: 1

Laurel
Laurel

Reputation: 6173

([&?]+)foo=.*?(?:&|$) should work.

What I changed

  • .*? fixes greediness issues.
  • (?:&|$) is a non-capturing group. It either matches a & or it matches the line end (with $).

Upvotes: 1

Related Questions