JavaScript URL Validation and Parsing Guide
The JavaScript URL API provides a built-in,
standards-compliant interface for parsing, validating, and decomposing
absolute web addresses into individual components. Rather than relying
on fragile custom regular expressions, developers can use the native
URL constructor and its companion methods to ensure an
address adheres to the WHATWG URL standard while simultaneously
extracting properties such as the protocol, host, path, and query
parameters.
Validating Absolute URLs
The URL interface validates strings during object
instantiation. When a string is passed to the URL
constructor, it automatically checks if the string represents a
syntactically valid absolute URL.
Validation Using
try...catch
If a string is invalid or lacks an absolute base scheme (such as
https://), the constructor throws a TypeError.
You can validate an address by wrapping the instantiation in a
try...catch block:
function isValidUrl(urlString) {
try {
new URL(urlString);
return true;
} catch (err) {
return false;
}
}
console.log(isValidUrl("https://example.com/path")); // true
console.log(isValidUrl("not-a-valid-url")); // falseValidation Using
URL.canParse()
Modern JavaScript runtimes (Node.js 19.9.0+ and modern browsers)
support the static URL.canParse() method, which performs
the same validation logic and returns a boolean directly:
const isValid = URL.canParse("https://example.com/api?user=123"); // true
const isInvalid = URL.canParse("/relative/path"); // falseDecomposing URL Components
Once an absolute URL string is parsed into a URL
instance, the object exposes read/write properties that decompose the
address into its constituent parts.
Consider the following URL:
https://user:secret@example.com:8080/docs/search?query=javascript#results
const parsedUrl = new URL("https://user:secret@example.com:8080/docs/search?query=javascript#results");The URL instance breaks this address down into the
following properties:
href: The entire serialized and normalized URL string (https://user:secret@example.com:8080/docs/search?query=javascript#results).origin: The scheme and authority of the URL without credentials (https://example.com:8080).protocol: The scheme followed by a colon (https:).username: The authentication username (user).password: The authentication password (secret).host: The domain name and port combination (example.com:8080).hostname: The domain name or IP address alone, excluding the port (example.com).port: The port number as a string (8080). If the URL uses a standard default port (like80for HTTP or443for HTTPS), this property returns an empty string.pathname: The hierarchical path starting with a forward slash (/docs/search).search: The query string, including the leading question mark (?query=javascript).hash: The fragment identifier, including the leading hash symbol (#results).
Working with Query Parameters
The URL object includes the searchParams
property, which exposes a URLSearchParams instance to
inspect and manipulate query strings without manual string
splitting:
const url = new URL("https://example.com/filter?category=books&sort=asc&page=2");
// Reading query parameters
console.log(url.searchParams.get("category")); // "books"
console.log(url.searchParams.has("sort")); // true
// Modifying and appending parameters
url.searchParams.set("page", "3");
url.searchParams.append("tag", "web");
console.log(url.toString());
// "https://example.com/filter?category=books&sort=asc&page=3&tag=web"Normalization and Mutability
The URL constructor automatically normalizes input
strings by converting hostnames to lowercase, resolving relative path
segments (like .. and .), and encoding special
characters. Furthermore, updating any single property (such as
url.pathname = "/new-path") automatically updates the other
corresponding properties and the complete url.href
output.