0

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

5
  • Did you try using the global flag /g? Commented Jul 3, 2020 at 13:38
  • @Thefourthbird no, not sure where it would go? Commented Jul 3, 2020 at 13:40
  • @Mandy8055 the regex you suggested only matches the first? thanks! Commented Jul 3, 2020 at 13:54
  • If you want to replace the groups with different values, you might check for the value of each group. See ideone.com/cT45xR Commented Jul 3, 2020 at 14:11
  • 1
    @Mandy8055 You already have given a good answer, feel free to add or adjust it. Commented Jul 3, 2020 at 14:40

1 Answer 1

2

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.

Pictorial Representation

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);

Sign up to request clarification or add additional context in comments.

3 Comments

The first solution does work but how can I get the remaining string rather than the extracted querystrings? The regex matches the first but not both.
Yes I want to remove those two querystrings and their values while leaving the rest of the url intact.. no extra & etc. Thanks!
Thanks to @Thefourthbird for suggesting a beautiful enhancement in the mentioned regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.