Reputation: 110143
I have the following two urls:
url1 = http://localhost:8000/i/dashboard-view?
&level_to_load=1&click_value=%C2%AB%20backll%20Billing%20PartiesC2%
AB%20backll%20Billing%20Parties
url2 = http://localhost:8000/i/dashboard-view?&level_to_load=1
&click_value=%C2%AB%20backll%20Billing%20PartiesC2%AB%20backll%20Billing%20Parties
&new_value=2
I want to be able to pull out the part that contains "click_value=...".
The resulting two urls after the regular expression should then be:
url1 = http://localhost:8000/i/dashboard-view?&level_to_load=1
url2 = http://localhost:8000/i/dashboard-view?&level_to_load=1&new_value=2
The current regex I have is:
url.replace(/click_value=.+&/, '');
But it is obviously insufficient. What would be the correct regex here?
Upvotes: 1
Views: 70
Reputation: 41838
You can match the click_value
GET strings with this regex:
&?click_value=[^&#\s]*
Therefore, to nix them,
result = url.replace(/&?click_value=[^&#\s]*/mg, "");
Discussion
The key here is matching the right number of characters and no more. I revised my original answer after @ridgerunner's insightful observation that in many urls, though maybe not in yours, there can be an anchor tag at the end, starting with #
, which we don't want to replace. Thanks to him for the improved answer, which no longer uses lookaheads.
Token-by-Token
&? # '&' (optional (matching the most amount
# possible))
click_value= # 'click_value='
[^&#\s]* # any character except: '&', '#', whitespace
# (\n, \r, \t, \f, and " ") (0 or more times
# (matching the most amount possible))
Upvotes: 2