This live example demonstrates how to use the URL.parse() static method for a few different absolute and relative reference values.
#log {
height: 100px;
overflow: scroll;
padding: 0.5rem;
border: 1px solid black;
}
const logElement = document.getElementById("log");
function log(text) {
logElement.innerText += `${text}\n`;
}
First we check that the URL.parse() method is supported using the condition "parse" in URL.
If the method is supported we log the result of checking an absolute URL, a relative reference and a base URL, a relative reference with a more complicated base URL, a valid absolute URL with a valid base URL (which is not used), and an invalid base URL that results in the method returning null.
We also log the case when URL.parse() is not supported.
js
if ("parse" in URL) {
// Absolute URL
let result = URL.parse("https://developer.mozilla.org/en-US/docs");
log(`[1]: ${result.href}`);
// Relative reference to a valid base URL
result = URL.parse("en-US/docs", "https://developer.mozilla.org");
log(`[2]: ${result.href}`);
// Relative reference to a "complicated" valid base URL
// (only the scheme and domain are used to resolve url)
result = URL.parse(
"/different/place",
"https://developer.mozilla.org:443/some/path?id=4",
);
log(`[3]: ${result.href}`);
// Absolute url argument (base URL ignored)
result = URL.parse(
"https://example.org/some/docs",
"https://developer.mozilla.org",
);
log(`[4]: ${result.href}`);
// Invalid base URL (missing colon)
result = URL.parse("en-US/docs", "https//developer.mozilla.org");
log(`[5]: ${result}`);
} else {
log("URL.parse() not supported");
}
Last of all, the code below demonstrates that the arguments don't have to be strings, by passing an URL object for the base parameter.
js
if ("parse" in URL) {
// Relative reference with base URL supplied as a URL object
result = URL.parse("/en-US/docs", new URL("https://developer.mozilla.org/"));
log(`[6]: ${result.href}`);
}
The results of each of the checks are shown below.