'Adding a slash after hostname and before query params

I need to add a slash in case there is no path in url before "?" query params.

For instance https://www.example.com?foo=bar turns out to be https://www.example.com/?foo=bar

This change i only need to do once in a url:

https://www.example.com?foo=bar&url=https://www.example.com?aa=b will be https://www.example.com/?foo=bar&url=https://www.example.com?aa=b

Also, In case there is path, no don't need to add this slash https://www.example.com/path?foo=bar will remain https://www.example.com/path?foo=bar

Would really appreciate the help.



Solution 1:[1]

Use the built-in URL interface when creating URLs and it will get them right for you, especially if you use the attached searchParams (URLSearchParams) for manipulating query parameters.

const base = "https://example.com";

const url1 = new URL(base);
url1.searchParams.append("foo", "bar");
console.log(url1.toString());
  // ? https://example.com/?foo=bar

// Query parameters will be encoded correctly
url1.searchParams.append("url", "https://www.example.com?aa=b");
console.log(url1.toString());
  // ? https://example.com/?foo=bar&url=https%3A%2F%2Fwww.example.com%3Faa%3Db

const url2 = new URL("/path", base);
url2.searchParams.append("foo", "bar");
console.log(url2.toString());
  // ? https://example.com/path?foo=bar

Solution 2:[2]

url = 'https://www.example.com?foo=bar&url=https://www.example.com?aa=b'
url = url.match(/com\/\?/) ? url : url.replace('com?', 'com/?')
console.log(url)

url = 'https://www.example.com/?foo=bar&url=https://www.example.com?aa=b'
url = url.match(/com\/\?/) ? url : url.replace('com?', 'com/?')
console.log(url)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phil
Solution 2