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 11 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
137 changes: 137 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,137 @@
---
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 is used to resolve the final absolute 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`.

When specify a `base` URL, the resolved URL is not simply a concatenation of `url` and `base`.
hamishwillee marked this conversation as resolved.
Show resolved Hide resolved
Parent-relative and current-directory-relative URLS are relative to the current directory of the `base` URL, which includes only path segments up until the last forward-slash, but not any after.
hamishwillee marked this conversation as resolved.
Show resolved Hide resolved
Root-relative URLs are relative to the base origin.
For more information see [Resolving relative URLs](/en-US/docs/Web/API/URL_API/Resolving_relative_urls).

> **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

[Resolving relative URLs](/en-US/docs/Web/API/URL_API/Resolving_relative_urls) and [`URL()` constructor](/en-US/docs/Web/API/URL/URL#examples) provide additional examples demonstrating how different `url` and `base` values are resolved to a final absolute URL (though primarily using `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: 100px;
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 an absolute URL, a relative URL with a base URL, a relative URL with a more [complicated base URL](/en-US/docs/Web/API/URL_API/Resolving_relative_urls), 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 URL resolved to valid base URL
result = URL.parse("en-US/docs", "https://developer.mozilla.org");
log(`[2]: ${result.href}`);

// Relative URL resolved to "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 URL 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.

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

## 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
- [A polyfill of `URL.parse()`](https://github.com/zloirock/core-js#url-and-urlsearchparams) is available in [`core-js`](https://github.com/zloirock/core-js)
87 changes: 26 additions & 61 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,37 +22,33 @@ 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 is used to resolve the final absolute 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, 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.

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).
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.
See the examples under [Examples - Merging of url and base paths](#merging_of_url_and_base_paths).

- : A string representing the base URL to use in cases where `url` is a relative URL.
If not specified, it defaults to `undefined`.

When specify a `base` URL, the resolved URL is not simply a concatenation of `url` and `base`.
Parent-relative and current-directory-relative URLS are relative to the current directory of the `base` URL, which includes path segments up until the last forward-slash, but not any after.
Root-relative URLs are relative to the base origin.
For more information see [Resolving relative URLs](/en-US/docs/Web/API/URL_API/Resolving_relative_urls).

> **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.

### 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
Here are some examples of using the constructor.

> **Note:** [Resolving relative URLs](/en-US/docs/Web/API/URL_API/Resolving_relative_urls) provides additional examples demonstrating how different `url` and `base` values are resolved to a final absolute URL.

```js
// Base URLs:
let baseUrl = "https://developer.mozilla.org";
Expand All @@ -79,9 +73,11 @@ new URL("/en-US/docs", A);

new URL("/en-US/docs", "https://developer.mozilla.org/fr-FR/toto");
// => 'https://developer.mozilla.org/en-US/docs'
```

// Invalid URLs:
Here are some examples of invalid URLs:

```js
new URL("/en-US/docs", "");
// Raises a TypeError exception as '' is not a valid URL

Expand All @@ -106,38 +102,6 @@ new URL("//foo.com", "https://example.com");
// => 'https://foo.com/' (see relative URLs)
```

### Merging of url and base paths
hamishwillee marked this conversation as resolved.
Show resolved Hide resolved

```js
/* base path without trailing slash */

const A = new URL("articles", "https://developer.mozilla.org/api/v1");
// => 'https://developer.mozilla.org/api/articles'

const B = new URL("/articles", "https://developer.mozilla.org/api/v1");
// => 'https://developer.mozilla.org/articles'

const C = new URL("./articles", "https://developer.mozilla.org/api/v1");
// => 'https://developer.mozilla.org/api/articles'

const D = new URL("../articles", "https://developer.mozilla.org/api/v1");
// => 'https://developer.mozilla.org/articles'

/* base path with trailing slash */

const E = new URL("articles", "https://developer.mozilla.org/api/v1/");
// => 'https://developer.mozilla.org/api/v1/articles'

const F = new URL("/articles", "https://developer.mozilla.org/api/v1/");
// => 'https://developer.mozilla.org/articles'

const G = new URL("./articles", "https://developer.mozilla.org/api/v1/");
// => 'https://developer.mozilla.org/api/v1/articles'

const H = new URL("../articles", "https://developer.mozilla.org/api/v1/");
// => 'https://developer.mozilla.org/api/articles'
```

## Specifications

{{Specifications}}
Expand All @@ -148,5 +112,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")}}.
Loading