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

FF115 URL.canParse() supported #27266

Merged
merged 6 commits into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
110 changes: 110 additions & 0 deletions files/en-us/web/api/url/canparse_static/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
---
title: "URL: canParse() static method"
short-title: canParse()
slug: Web/API/URL/canParse_static
page-type: web-api-static-method
browser-compat: api.URL.canParse_static
---

{{ApiRef("URL API")}}

The **`URL.canParse()`** static method of the {{domxref("URL")}} interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid.

This a fast and easy alternative to constructing a `URL` within a [try...catch](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) block.
It returns `true` for the same values for which the [`URL()` constructor](/en-US/docs/Web/API/URL/URL) would succeed, and `false` for the values that would cause the constructor to throw.

## Syntax

```js-nolint
URL.canParse(url)
URL.canParse(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.
- `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 be stringified to the object's {{domxref("URL.href", "href")}} property.

### Return value

`true` if the URL can be parsed and is valid; `false` otherwise.

## Examples

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

The first part of the example defines an HTML `<pre>` element to log to, along with a logging method `log()`.

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

```js
const logElement = document.getElementById("log");
function log(text) {
logElement.innerText += `${text}\n`;
}
```

Next we check that the `URL.canParse()` method is supported using the condition `"canParse" in URL`.
If the method is supported we log the result of checking an absolute URL, a relative URL with no base URL, and a relative URL with a valid base URL.
We also log the case when `URL.canParse()` is not supported.

```js
if ("canParse" in URL) {
log("Test valid absolute URL");
let url = "https://developer.mozilla.org/";
let result = URL.canParse(url);
log(` URL.canParse("${url}"): ${result}`);

log("\nTest relative URL with no base URL");
url = "/en-US/docs";
result = URL.canParse(url);
log(` URL.canParse("${url}"): ${result}`);

log("\nTest relative URL with valid base URL");
let baseUrl = "https://developer.mozilla.org/";
result = URL.canParse(url, baseUrl);
log(` URL.canParse("${url}","${baseUrl}"): ${result}`);
} else {
log("URL.canParse() 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 ("canParse" in URL) {
log("\nTest relative URL with base URL supplied as a URL object");
let baseUrl = new URL("https://developer.mozilla.org/");
let url = "/en-US/docs";
result = URL.canParse(url, baseUrl);
log(` URL.canParse("${url}","${baseUrl}"): ${result}`);
}
```

The results of each of the checks are shown below.

{{EmbedLiveSample('Examples', '100%', '200')}}

## Specifications

{{Specifications}}

## Browser compatibility

{{Compat}}

## See also

- {{domxref("URL.URL", "URL()")}}
- [A polyfill of `URL.canParse()`](https://github.com/zloirock/core-js#url-and-urlsearchparams) is available in [`core-js`](https://github.com/zloirock/core-js)
15 changes: 15 additions & 0 deletions files/en-us/web/api/url/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ If a browser doesn't yet support the {{domxref("URL.URL", "URL()")}} constructor

## Static methods

- [`canParse()`](/en-US/docs/Web/API/URL/canParse_static)
- : 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", "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.revokeObjectURL", "revokeObjectURL()")}}
Expand All @@ -71,6 +73,19 @@ console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"
```

The constructor with raise an exception if the URL cannot be parsed to a valid URL.
You can either call the above code in a [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) block or use the [`canParse()`](/en-US/docs/Web/API/URL/canParse_static) static method to first check the URL is valid:

```js
if (URL.canParse("../cats", "http://www.example.com/dogs")) {
const url = new URL("../cats", "http://www.example.com/dogs");
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"
} else {
console.log("Invalid URL"); //Invalid URL
}
```

URL properties can be set to construct the URL:

```js
Expand Down