Reputation: 1419
I have a url like:
http://example.org/someparam=asdfadfsadf&lmnop=Lasda:sdf&radParam=dfadfs&qrstu=asfasdf:asaasd
I have this regex:
/(&|\?)(lmnop|qrstu)=.*?(&|$)/
But I want to match both not just the first?
The desired result is the url with the two querystring params and their values removed:
http://example.org/someparam=asdfadfsadf&radParam=dfadfs
Upvotes: 0
Views: 39
Reputation:
1st approach without using regex:
Proposed Idea:
1. Split the string on & symbol.
2. Filter out those elements of the split string in step 1 which starts with lmnop= or qrstu=.
3. Join again on & symbol.
Please find the sample implementation below:
let string = `http://example.org/someparam=asdfadfsadf&lmnop=Lasda:sdf&radParam=dfadfs&qrstu=asfasdf:asaasd`;
console.log(
// Step 1
string.split("&").
// Step 2
filter(el => !(el.startsWith("lmnop=") || el.startsWith("qrstu="))).
// Step 3
join("&")
);
2nd Approach Using regex:
You may try:
&(?:lmnop|qrstu)=(.*?)(?=&|$)
Explanation of the above regex:
&
- Matches &
literally.(?:lmnop|qrstu)
- Represents a non-capturing group matching lmnop
or qrstu
.=
- Matches =
literally.(.*?)
- Lazily matches everything till the end or &
.(?=&|$)
- Represents a positive look-ahead which asserts end or &
.You can find the demo of the above regex in here.
const regex = /&(?:lmnop|qrstu)=(.*?)(?=&|$)/gm;
const str = `http://example.org/someparam=asdfadfsadf&lmnop=Lasda:sdf&radParam=dfadfs&qrstu=asfasdf:asaasd`;
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
Upvotes: 2