KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I'm looking for a regular expression to remove a single parameter from a query string, and I want to do it in a single regular expression if possible. Say I want to remove the foo parameter. Right now I use this: /&?foo\=[^&]+/ That works as long as foo is not the first parameter in the query string. If it is, then my new query string starts with an ampersand. (For example, " foo=123&bar=456 " gives a result of " &bar=456 ".) Right now, I'm just checking after the regex if the query string starts with ampersand, and chopping it off if it does. Example edge cases: Input | Expected Output -------------------------+-------------------- foo=123 | (empty string) foo=123&bar=456 | bar=456 bar=456&foo=123 | bar=456 abc=789&foo=123&bar=456 | abc=789&bar=456 Edit OK as pointed out in comments there are there are way more edge cases than I originally considered. I got the following regex to work with all of them: /&foo(\=[^&]*)?(?=&|$)|^foo(\=[^&]*)?(&|$)/ This is modified from Mark Byers's answer , which is why I'm accepting that one, but Roger Pate's input helped a lot too. Here is the full suite of test cases I'm using, and a Javascript snippet which tests them: $(function() { var regex = /&foo(\=[^&]*)?(?=&|$)|^foo(\=[^&]*)?(&|$)/; var escapeHtml = function (str) { var map = { '&': '&
Tags (comma-separated)
Save Edits
Cancel