0

I have the above string I want to remove gsi along with the value. After removing gsi my string should look like given below.

Scenario 1

/product/Abrasives?gsi=1

Expected output

/product/Abrasives

Scenario 2

/product/Abrasives?query=search&gsi=1

Expected output /product/Abrasives?query=search

Scenario 3

/product/Abrasives?query=search&gsi=1&fname=abc

Expected output

/product/Abrasives?query=search&fname=abc
Jitendra Rathor
  • 607
  • 8
  • 11
  • See answer here: https://stackoverflow.com/questions/1634748/how-can-i-delete-a-query-string-parameter-in-javascript – Jayce444 May 20 '21 at 04:41

1 Answers1

1

You could use the URL constructor and delete the parameter:

const paths = ["/product/Abrasives?gsi=1", "/product/Abrasives?query=search&gsi=1", "/product/Abrasives?query=search&gsi=1&fname=abc"]

function removeParam(path, name) {
  const url = new URL(path, "https://a.com")
  url.searchParams.delete(name)
  return url.pathname + url.search
}

console.log(
  paths.map(p => removeParam(p, "gsi"))
)

Or you could split at ? get the querystring and pathname separately. Use the URLSearchParams constructor and delete the parameter

const paths = ["/product/Abrasives?gsi=1", "/product/Abrasives?query=search&gsi=1", "/product/Abrasives?query=search&gsi=1&fname=abc"]

function removeParam(path, name) {
  const [pathName, queryString] = path.split('?');
  const searchParams = new URLSearchParams(queryString);
  searchParams.delete(name);
  return pathName + searchParams
}

console.log(
  paths.map(p => removeParam(p, "gsi"))
)
adiga
  • 34,372
  • 9
  • 61
  • 83