Constructing URLs is a common task in the frontend world.
Previously, we made use of the metal-uri module.
We now recommend using the native URL API.
Make sure you read the documentation referenced above to make sure you fully understand the URL API.
Additionally, a polyfill is also served for Internet Explorer 11, to ensure the URL
API can be used correcly.
// Note: To create relative URLs the second argument of the URL constructor is required.
const baseUrl = 'http://localhost:8080';
const guestUrl = new URL('/web/guest', baseUrl);
console.log(`The guest URL is ${guestUrl}`); // The guest URL is http://localhost:8080/web/guest
const portalUrl = new URL('http://localhost:8080');
console.log(`The portal URL is ${portalUrl}`); // The portal URL is http://localhost:8080
const myUrl = new URL('http://localhost:8080');
myUrl.searchParams.set('foo', 0);
myUrl.searchParams.set('bar', 'baz');
console.log(myUrl.toString()); // http://localhost:8080/?foo=0&bar=baz
You might need to set multiple values for the same parameter.
While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3
).
In order to acheive this behaviour, you can use the append
method of the URLSearchParams
interface.
const myUrl = new URL('http://localhost:8080/?foo=baz');
myUrl.searchParams.append('foo', 'another-baz');
console.log(myUrl.toString()); // http://localhost:8080/?foo=baz&foo=another-baz
const myUrl = new URL('http://localhost:8080/?foo=baz&bar=qux');
myUrl.searchParams.has('foo')); // true
myUrl.searchParams.has('bar')); // true
myUrl.searchParams.has('not-there'); // false
const myUrl = new URL('http://localhost:8080/?foo=baz&bar=qux');
myUrl.searchParams.get('foo'); // 'baz'
myUrl.searchParams.get('bar'); // 'qux'
myUrl.searchParams.get('not-there'); // null;
const myUrl = new URL('http://localhost:8080/?foo=baz&bar=qux');
myUrl.searchParams.delete('foo');
console.log(myUrl.toString()); // http://localhost:8080/?bar=qux
Please visit the MDN documentation on the URL API for more information.