Reputation: 25383
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.
Upvotes: 1
Views: 97
Reputation: 67505
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
Reputation: 34152
str = str.replace(/(?:\?|&)(foo[^=]*=[^&]+)(?:&|$)/,'');
Upvotes: 1
Reputation: 6173
([&?]+)foo=.*?(?:&|$)
should work.
.*?
fixes greediness issues.(?:&|$)
is a non-capturing group. It either matches a &
or it matches the line end (with $
).Upvotes: 1