0

I am trying to add params to a path only url (as somewhere else in my code works out the origin), but I'm running into an error in my below code because it doesn't see it as a valid url. (edit: also forgot to add a check that '/checkout/' exists in the path url)

function appendCountryParam(link, tag){
  var url = new URL(link); 
  url.searchParams.append('tag', tag); 
  return url.href;
}

I'm wondering if there's a clean way of adding params to path only urls. I have written a function myself, but it looks a bit too overcomplicated and I had directly translated my code from php to js.

function addTagParam(link, tag) {
  if (!link.includes('/checkout/')) {
    return link;
  }

  if (link.includes('?')) {
    const removeSlash = link.replace(/\/$/, '');
    return `${removeSlash}&tag=${tag}`;
  }

  const linkWithSlash = link.replace(/\/$|$/, '/');
  return `${linkWithSlash}?tag=${tag}`;
}

Edit: I'm passing in a path only url and I want it returned in the same format, but with the specified param, so something like this: /page/user/winsome/?tag=true

Winsome
  • 79
  • 1
  • 5
  • 12
  • I'm a little confused between first and second approach . can you give me an example of a correct output you wanna retrieve – Ayman Morsy Aug 12 '20 at 20:34
  • @AymanMorsy Yes, so I'm passing in a path only url and I want it returned in the same format, but with the specified param, so something like this: `/page/user/winsome/?tag=true` – Winsome Aug 12 '20 at 20:50
  • based on the first approach you provided Is that what you need : `function appendCountryParam(link, tag){ let url = new URL(`?tag=${tag}`,link); return url.href; } console.log(appendCountryParam('http://example.com',true))` – Ayman Morsy Aug 12 '20 at 21:04
  • Does this answer your question? [How to build query string with Javascript](https://stackoverflow.com/questions/316781/how-to-build-query-string-with-javascript) – JuanCaicedo Aug 13 '20 at 00:21

1 Answers1

0

Creating the string yourself like in your second example would be my preferred approach No need to add extra complexity unless you have many parameters.

If you do want to get fancy, you can instead append an instance of URLSearchParams (after you call .toString), like in this answer.

Dharman
  • 30,962
  • 25
  • 85
  • 135
JuanCaicedo
  • 3,132
  • 2
  • 14
  • 36
  • This is more like a comment than an answer; but your preferred approach also confuses me, because [`url.searchParams.append()`](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) is _less_ complex than properly managing the `?` and `&` yourself. – Stephen P Aug 13 '20 at 00:37