UNPKG

@gravityforms/utils

Version:
51 lines (45 loc) 1.74 kB
/** * @module normalizeUrl * @description Normalizes a URL by ensuring it starts with 'http://' or 'https://'. * It handles various cases including empty strings, existing protocols, and protocol-relative URLs. * * @since 4.0.4 * * @param {string} url The URL to be normalized. This can be a string representing a URL, an empty string, or a falsy value. * * @return {string} 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). * * @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( ' ' ); // '' * */ export default function normalizeUrl( url ) { if ( ! url ) { return ''; } const trimmedUrl = url.trim(); if ( trimmedUrl === '' ) { return ''; } if ( /^https?:\/\//i.test( trimmedUrl ) ) { return trimmedUrl; } if ( trimmedUrl.startsWith( '//' ) ) { return `https:${ trimmedUrl }`; } return `https://${ trimmedUrl }`; }