normalizeURL
normalizeURL
Normalizes a URL‑like value into a real URL instance or returns null.
This helper accepts native URL objects and string representations of absolute URLs. It never throws and never mutates input. Use it when you need a predictable, fully‑qualified URL before validation or further processing.
Signature
function normalizeURL(value: unknown): URL | null
Parameters
| Name | Data type | Description |
|---|---|---|
| value | unknown |
A value that may represent a TCP port number. |
Returns
One of:
URLinstance.null: If the value cannot be interpreted as an absolute URL.
Behavior
- If the value is already a URL, it is returned unchanged.
- If the value is a string:
- It is trimmed before parsing.
- It must represent a valid absolute URL.
- Relative URLs are rejected to avoid environment‑dependent resolution.
- All other values return
null. - The helper never throws and never mutates input.
Examples
normalizeURL("https://example.com/path");
// → URL("https://example.com/path")
normalizeURL(" https://example.com ");
// → URL("https://example.com/")
normalizeURL(new URL("https://example.com"));
// → same URL instance
normalizeURL("/relative/path");
// → null
normalizeURL("not a url");
// → null
Notes
- The WHATWG URL constructor is used for parsing.
- Relative URLs are intentionally rejected because the URL constructor resolves them against "about:blank", which is rarely desired.