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