Normalizes a URL by ensuring it starts with 'http://' or 'https://'. It handles various cases including empty strings, existing protocols, and protocol-relative URLs.
Parameters:
| Name | Type | Description |
|---|---|---|
url | string | The URL to be normalized. This can be a string representing a URL, an empty string, or a falsy value. |
- Since
- 4.0.4
- Source
Returns:
Returns the normalized URL. - If the input is falsy or an empty string (after trimming), returns an empty string. - If the input is a valid URL (starts with http:// or https://), returns it as is (after trimming). - If the input is a protocol-relative URL (starts with //), prepends 'https://' (after trimming). - Otherwise, prepends 'https://' to the input (after trimming).
- Type:
- string
Example
import { normalizeUrl } from "@gravityforms/utils";
normalizeUrl( 'example.com' ); // 'https://example.com'
normalizeUrl( ' http://example.com ' ); // 'http://example.com'
normalizeUrl( 'https://example.com' ); // 'https://example.com'
normalizeUrl( '//example.com' ); // 'https://example.com'
normalizeUrl( ' example.com/path?query=value ' ); // 'https://example.com/path?query=value'
normalizeUrl( null ); // ''
normalizeUrl( undefined ); // ''
normalizeUrl( '' ); // ''
normalizeUrl( ' ' ); // ''