URL

URL.canParse

Returns a boolean indicating whether or not the given URL string can be parsed into a valid URL

Syntax

JavaScript
URL.canParse(url, base?)

Parameters

ParameterTypeDescription
urlstringThe URL string to test
basestringAn optional base URL to resolve against

Return Value

true if the URL can be parsed, false otherwise

Examples

Basic Usage
console.log(URL.canParse('https://example.com')) // true
console.log(URL.canParse('not a url')) // false
Practical Example
const urls = ['https://example.com', 'bad', '/path']
const valid = urls.filter(u => URL.canParse(u))
console.log(valid)
Advanced Usage
function safeUrl(input: string, base?: string): URL | null {
  if (URL.canParse(input, base)) {
    return new URL(input, base)
  }
  return null
}

Understanding URL.canParse

The URL.canParse method in JavaScript returns a boolean indicating whether or not the given URL string can be parsed into a valid URL. It belongs to the URL object and is one of the most widely used methods for working with url values in modern JavaScript and TypeScript applications.

The method signature is URL.canParse(url, base?). It accepts 2 parameters: url, base. When called, it returns true if the url can be parsed, false otherwise. Understanding when and how to use canParse() helps you write more expressive, readable code.

Common use cases for URL.canParse include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like url-href, url-tostring, enabling you to chain operations together for complex data manipulation pipelines.

Supported in Chrome 120+, Firefox 115+, Safari 17+, Edge 120+, Node.js 20+.

Browser Compatibility

Supported in Chrome 120+, Firefox 115+, Safari 17+, Edge 120+, Node.js 20+.

Related Methods

More URL Methods

Other methods in the URL object

Related Tools

More URL Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.