Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

URL.parse() static method docs #33207

Merged
merged 14 commits into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion files/en-us/web/api/url/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ If a browser doesn't yet support the {{domxref("URL.URL", "URL()")}} constructor
## Constructor

- {{domxref("URL.URL", "URL()")}}
- : Creates and returns a `URL` object referencing the URL specified using an absolute URL string, or a relative URL string and a base URL string.
- : Creates and returns a `URL` object from a URL string and optional base URL string.
Throws if the passed arguments don't define a valid URL.

## Instance properties

Expand Down Expand Up @@ -51,6 +52,8 @@ If a browser doesn't yet support the {{domxref("URL.URL", "URL()")}} constructor
- : Returns a boolean indicating whether or not a URL defined from a URL string and optional base URL string is parsable and valid.
- {{domxref("URL.createObjectURL_static", "createObjectURL()")}}
- : Returns a string containing a unique blob URL, that is a URL with `blob:` as its scheme, followed by an opaque string uniquely identifying the object in the browser.
- {{domxref("URL.parse_static", "parse()")}}
- : Creates and returns a `URL` object from a URL string and optional base URL string, or returns `null` if the passed parameters define an invalid `URL`.
- {{domxref("URL.revokeObjectURL_static", "revokeObjectURL()")}}
- : Revokes an object URL previously created using {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}.

Expand Down
120 changes: 120 additions & 0 deletions files/en-us/web/api/url/parse_static/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
---
title: "URL: parse() static method"
short-title: parse()
slug: Web/API/URL/parse_static
page-type: web-api-static-method
browser-compat: api.URL.parse_static
---

{{ApiRef("URL API")}}

The **`URL.parse()`** static method of the {{domxref("URL")}} interface returns a newly created {{domxref("URL")}} object representing the URL defined by the parameters.

If the given base URL or the resulting URL are not parsable and valid URLs, `null` is returned.
This is an alternative to using the {{domxref("URL.URL", "URL()")}} constructor to construct a `URL` within a [try...catch](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) block, or using {{domxref("URL.canParse_static", "canParse()")}} to check the parameters and returning `null` if the method returns `false`.

## Syntax

```js-nolint
URL.parse(url)
URL.parse(url, base)
```

### Parameters

- `url`
- : A string or any other object with a {{Glossary("stringifier")}} that represents an absolute or relative URL.
If `url` is a relative URL, `base` is required, and will be used as the base URL.
If `url` is an absolute URL, a given `base` will not be used to create the resulting URL.
- `base` {{optional_inline}}
- : A string representing the base URL to use in cases where `url` is a relative URL.
If not specified, it defaults to `undefined`.

> **Note:** The `url` and `base` arguments will each be stringified from whatever value you pass, such as an {{domxref("HTMLAnchorElement")}} or {{domxref("HTMLAreaElement")}} element, just like with other Web APIs that accept a string.
> In particular, you can use an existing {{domxref("URL")}} object for either argument, and it will be stringified from the object's {{domxref("URL.href", "href")}} property.

### Return value

A `URL` if the parameters can be resolved to a valid URL; `null` otherwise.

## Examples

The [`URL()` constructor](/en-US/docs/Web/API/URL/URL#examples) documentation provides many additional examples demonstrating how different `url` and `base` values are resolve to a final absolute URL.

### Using URL.parse()

This live example demonstrates how to use the `URL.parse()` static method for a few different absolute and relative URL values.

```html hidden
<pre id="log"></pre>
```

```css hidden
#log {
height: 250px;
overflow: scroll;
padding: 0.5rem;
border: 1px solid black;
}
```

```js hidden
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 a relative URL with a base URL, a valid absolute URL with a valid base URL (which gets ignored), and an invalid base URL that returns `null`.

We also log the case when `URL.parse()` is not supported.

```js
if ("parse" in URL) {
let result = URL.parse("en-US/docs", "https://developer.mozilla.org");
log("//Relative URL appended to valid base URL");
hamishwillee marked this conversation as resolved.
Show resolved Hide resolved
log(`Url.parse("${url}", "${base}")\n// ${result}`);
hamishwillee marked this conversation as resolved.
Show resolved Hide resolved

url = "https://example.org/some/docs";
result = URL.parse(url, base);
log("\n//Absolute URL (base URL ignored)");
hamishwillee marked this conversation as resolved.
Show resolved Hide resolved
log(`Url.parse("${url}", "${base}")\n// => ${result}`);
hamishwillee marked this conversation as resolved.
Show resolved Hide resolved

log("\n//Invalid base URL (missing colon)");
hamishwillee marked this conversation as resolved.
Show resolved Hide resolved
base = "https//developer.mozilla.org";
result = URL.parse(url, base);
log(`Url.Parse("${url}", "${base}")\n// ${result}`);
} else {
log("URL.parse() not supported");
}
```

Last of all, the code below shows that the `baseUrl` doesn't have to be a string.
Here we have passed a `URL` object.

```js
if ("parse" in URL) {
log("\nRelative URL with base URL supplied as a URL object");
hamishwillee marked this conversation as resolved.
Show resolved Hide resolved
base = new URL("https://developer.mozilla.org/");
url = "/en-US/docs";
result = URL.parse(url, base);
log(`Url.parse("${url}", "${base}")\n// ${result}`);
}
```

The results of each of the checks are shown below.

{{EmbedLiveSample('URL.parse()', '100%', '300')}}

## Specifications

{{Specifications}}

## Browser compatibility

{{Compat}}

## See also

- [`URL()` constructor](/en-US/docs/Web/API/URL/URL), which throws if the passed parameters define an invalid URL
hamishwillee marked this conversation as resolved.
Show resolved Hide resolved
37 changes: 14 additions & 23 deletions files/en-us/web/api/url/url/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,9 @@ browser-compat: api.URL.URL

{{APIRef("URL API")}} {{AvailableInWorkers}}

The **`URL()`** constructor returns a newly created
{{domxref("URL")}} object representing the URL defined by the parameters.
The **`URL()`** constructor returns a newly created {{domxref("URL")}} object representing the URL defined by the parameters.

If the given base URL or the resulting URL are not valid URLs, the JavaScript
{{jsxref("TypeError")}} exception is thrown.
If the given base URL or the resulting URL are not valid URLs, the JavaScript {{jsxref("TypeError")}} exception is thrown.

## Syntax

Expand All @@ -24,34 +22,26 @@ new URL(url, base)
### Parameters

- `url`
- : A string or any other object with a {{Glossary("stringifier")}} — including, for example, an {{htmlelement("a")}} or {{htmlelement("area")}} element — that represents an absolute or relative URL.
If `url` is a relative URL, `base` is
required, and will be used as the base URL. If `url` is an
absolute URL, a given `base` will be ignored.
- : A string or any other object with a {{Glossary("stringifier")}} that represents an absolute or relative URL.
If `url` is a relative URL, `base` is required, and will be used as the base URL.
If `url` is an absolute URL, a given `base` will not be used to create the resulting URL.
- `base` {{optional_inline}}
- : A string representing the base URL to use in cases where
`url` is a relative URL. If not specified, it defaults to
`undefined`.
- : A string representing the base URL to use in cases where `url` is a relative URL.
If not specified, it defaults to `undefined`.

> **Note:** The `url` and `base` arguments will
> each be stringified from whatever value you pass, just like with other Web APIs
> that accept a string. In particular, you can use an existing
> {{domxref("URL")}} object for either argument, and it will stringify to the
> object's {{domxref("URL.href", "href")}} property.
> **Note:** The `url` and `base` arguments will each be stringified from whatever value you pass, such as an {{domxref("HTMLAnchorElement")}} or {{domxref("HTMLAreaElement")}} element, just like with other Web APIs that accept a string.
> In particular, you can use an existing {{domxref("URL")}} object for either argument, and it will be stringified from the object's {{domxref("URL.href", "href")}} property.

The resulting URL is not simply a concatenation of `url` and `base`.
The path sections of both arguments are merged according to
[RFC 3986 - Relative Resolution](https://datatracker.ietf.org/doc/html/rfc3986.html#section-5.2).
The path sections of both arguments are merged according to [RFC 3986 - Relative Resolution](https://datatracker.ietf.org/doc/html/rfc3986.html#section-5.2).
Therefore a trailing slash in `base` or a leading slash in `url` affect how the resulting path is constructed.
If you need a strict concatenation of the two arguments the `url` must not have a leading slash
and the `base` must have a trailing slash.
If you need a strict concatenation of the two arguments the `url` must not have a leading slash and the `base` must have a trailing slash.
hamishwillee marked this conversation as resolved.
Show resolved Hide resolved
See the examples under [Examples - Merging of url and base paths](#merging_of_url_and_base_paths).

### Exceptions

| Exception | Explanation |
| ----------------------- | --------------------------------------------------------------------------------------------------------- |
| {{jsxref("TypeError")}} | `url` (in the case of absolute URLs) or `base` + `url` (in the case of relative URLs) is not a valid URL. |
- {{jsxref("TypeError")}}
- : `url` (in the case of absolute URLs) or `base` + `url` (in the case of relative URLs) is not a valid URL.

## Examples

hamishwillee marked this conversation as resolved.
Show resolved Hide resolved
Expand Down Expand Up @@ -148,5 +138,6 @@ const H = new URL("../articles", "https://developer.mozilla.org/api/v1/");

## See also

- {{domxref("URL.parse_static", "URL.parse()")}}, a non-throwing alternative to this constructor
- [Polyfill of `URL` in `core-js`](https://github.com/zloirock/core-js#url-and-urlsearchparams)
- The interface it belongs to: {{domxref("URL")}}.