# URL.canParse()

> The `URL.canParse()` static JS method checks whether a string can be parsed as a valid URL.

## How do I check if a string is a valid URL in JavaScript?

The static method that returns `true` if the string, optionally with a base URL, is a valid URL. Allows validating URLs without wrapping the `URL` constructor in a `try...catch` block.

- Topic: Navigation in Browser
- Type: method
- Browser support: Chrome 120+, Chrome Android 120+, Edge 120+, Firefox 115+, Firefox Android 115+, Safari 17+, Safari iOS 17+

## Example

Wrong:

```js
function isValidUrl(str) {
  try {
    new URL(str);
    return true;
  } catch {
    return false;
  }
}
```

Right:

```js
function isValidUrl(str) {
  return URL.canParse(str);
}
```

`URL.canParse()` gives the same answer as `new URL()` without throwing or creating an object.

## Common mistakes

- Treating a URL as safe just because it parses.

## Key points

- The check uses `URL.canParse()` instead of a regex or a `try...catch` around `new URL()`.
- Relative URLs are checked with a base, as in `URL.canParse(path, location.origin)`.
- Links from users also check the scheme, because 'javascript:' URLs parse as valid.

## Interview questions

### Does URL.canParse() accept relative URLs?

Only with a base. `URL.canParse('/about')` is false, while `URL.canParse('/about', 'https://example.com')` is true.

### Does URL.canParse() check that the URL exists?

No. It checks only the syntax and makes no network request.

### What if I need the parsed URL too?

Use `URL.parse()`, which returns a `URL` object or `null` instead of throwing, or `new URL()` inside `try...catch`.

## Related cards

- [URLPattern](https://wonderium.dev/js/url-pattern.md)
- [URLSearchParams](https://wonderium.dev/js/url-search-params.md)
- [URL](https://wonderium.dev/web/url.md)
- [location](https://wonderium.dev/js/location.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/url-can-parse
- Last updated: 2026-11-25
