The input string to sanitize as a URL.
Optional settings to customize behavior.
Optional
allowedProtocols?: string[]Array of allowed URL protocols (including colon). Defaults to ['http:', 'https:', 'ftp:'].
Optional
normalize?: booleanIf true (default), returns a normalized URL string. If false, returns the original input string when valid.
An object indicating success, sanitized value, and optional error.
// ES Module
import { sanitizeUrl } from '@bnidev/js-utils'
// CommonJS
const { sanitizeUrl } = require('@bnidev/js-utils')
sanitizeUrl('https://example.com')
// → { success: true, value: 'https://example.com/' }
sanitizeUrl('mailto:user@example.com')
// → { success: false, value: null, error: Error('Disallowed protocol: mailto:') }
sanitizeUrl('mailto:user@example.com', { allowedProtocols: ['mailto:'] })
// → { success: true, value: 'mailto:user@example.com' }
sanitizeUrl('invalid-url')
// → { success: false, value: null, error: Error('Invalid URL') }
Sanitizes a URL string by validating its syntax and protocol.
Ensures the input is a valid URL and the protocol is included in the allowed list. By default, allows only
http:
,https:
, andftp:
protocols for safety. Users can override or extend the allowed protocols via options.