0

I want remove the duplicate word with regex

let url = "/courses?category=programming&filter=free&filter=free"
const az = url.replace(/(\b\S.+\b)(?=.*\1)/g, "").trim();
console.log(az) // /courses?category=programmingfree&filter=free

I want to get /courses?category=programming&filter=free

2
  • 1
    It looks like you do not want to find "words", but the whole query params. Commented Oct 9, 2021 at 21:01
  • I dont understand regex if anyone now, please write the correct form of regex Commented Oct 9, 2021 at 21:08

1 Answer 1

6

You can use the URLSearchParams constructor to parse the URL parameters, then Object.fromEntries to convert it to an object (and remove duplicate keys), then parse back into a URLSearchParams object, from which you can call toString() to get the result:

let url = "/courses?category=programming&filter=free&filter=free"
let [path, params] = url.split("?");
let result = path + '?' + new URLSearchParams(Object.fromEntries(new URLSearchParams(params))).toString()
console.log(result)

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

3 Comments

It will not work when we have to pass values in array format
@Meet what do you mean "array format?" The standard way to pass multiple GET values is to assign the value more than once.
I am taking multiple inputs as <input name="filters[]" value="1" /> because of our work flow, and when I submit form, it will pass multiple filters[] keys in URL, We can't control that as per my knowledge, It will be great, if you have answer for it

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.