Node.js Reference ยท path, os and url
Node.js URL.canParse() method
Reference for URL.canParse() in Node.js: check whether a string is a valid URL, with or without a base, without try/catch, plus edge cases and pitfalls.
URL.canParse() is a static method that answers one question: would new URL(input, base) succeed? It returns true or false and never throws for bad URLs. Before it existed, validation meant wrapping the constructor in try/catch, which is noisy and slow when many inputs are invalid.
Use it for yes/no checks such as form validation. If you also need the parsed result, call URL.parse() instead, which returns the object or null in a single parse.
URL.canParse('https://example.com/a'); // true URL.canParse('/a'); // false (no base) URL.canParse('/a', 'https://example.com'); // true
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
URL.canParse(input[, base])
| Name | Description |
|---|---|
input |
The string to test. Anything that is not a string is converted with String(). |
base |
Optional base URL string used to resolve a relative input. |
Returns: true if the constructor would succeed, otherwise false.
Errors: none for invalid URLs. Passing a symbol or an object whose toString() throws will still throw, because the conversion to string runs first.
Usage notes
canParse()only checks syntax.javascript:alert(1)anddata:URLs are "valid", so always checkprotocolyourself when the scheme matters.- A relative reference like
/docsneeds a base. If the base itself is invalid, the result isfalse. - A string with no scheme, such as
example.com, is not a URL. Parsing it fails unless you supply a base, in which case it becomes a relative path on that base. - The call parses the string once, and a following
new URL()parses it again. When you will use the result,URL.parse()avoids that duplicate work. - Added in Node.js 19.9 and 18.17. Earlier versions need
try/catch. truedoes not mean the host exists or is reachable, only that the text follows the WHATWG URL syntax.