From 4f66249c2a5946483554ead832bb68db724b612e Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Thu, 31 Mar 2022 21:01:17 +0200 Subject: [PATCH] fix(withProtocol): handle input without protocol (resolves #52) side effect: hasProtocol allows [protocol]:$ --- src/utils.ts | 11 +++++++++-- test/utilities.test.ts | 8 +++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index 1cd8656..d5cda38 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -7,8 +7,11 @@ export function isRelative (inputStr: string) { return ['./', '../'].some(str => inputStr.startsWith(str)) } +const PROTOCOL_REGEX = /^\w+:(\/\/)?/ +const PROTOCOL_RELATIVE_REGEX = /^\/\/[^/]+/ + export function hasProtocol (inputStr: string, acceptProtocolRelative = false): boolean { - return /^\w+:(\/\/)?.+/.test(inputStr) || (acceptProtocolRelative && /^\/\/[^/]+/.test(inputStr)) + return PROTOCOL_REGEX.test(inputStr) || (acceptProtocolRelative && PROTOCOL_RELATIVE_REGEX.test(inputStr)) } const TRAILING_SLASH_RE = /\/$|\/\?/ @@ -122,7 +125,11 @@ export function withoutProtocol (input: string): string { } export function withProtocol (input: string, protocol: string): string { - return input.replace(/^\w+:(\/\/)?/, protocol) + const match = input.match(PROTOCOL_REGEX) + if (!match) { + return protocol + input + } + return protocol + input.substring(match[0].length) } // $URL based utils diff --git a/test/utilities.test.ts b/test/utilities.test.ts index e9e220b..1cb1620 100644 --- a/test/utilities.test.ts +++ b/test/utilities.test.ts @@ -19,7 +19,7 @@ describe('hasProtocol', () => { { input: 'https://test.com', out: [true, true] }, { input: '/test', out: [false, false] }, { input: 'file:///home/user', out: [true, true] }, - { input: 'tel:', out: [false, false] }, + { input: 'tel:', out: [true, true] }, { input: 'tel:123456', out: [true, true] }, { input: 'mailto:support@example.com', out: [true, true] } ] @@ -75,7 +75,8 @@ describe('withHttp', () => { { input: 'https://example.com', out: 'http://example.com' }, { input: 'ftp://example.com/test?foo', out: 'http://example.com/test?foo' }, { input: 'https://foo.com/test?query=123#hash', out: 'http://foo.com/test?query=123#hash' }, - { input: 'file:///home/user', out: 'http:///home/user' } + { input: 'file:///home/user', out: 'http:///home/user' }, + { input: 'foo.bar.com', out: 'http://foo.bar.com' } ] for (const t of tests) { @@ -90,7 +91,8 @@ describe('withHttps', () => { { input: 'http://example.com', out: 'https://example.com' }, { input: 'ftp://example.com/test?foo', out: 'https://example.com/test?foo' }, { input: 'http://foo.com/test?query=123#hash', out: 'https://foo.com/test?query=123#hash' }, - { input: 'file:///home/user', out: 'https:///home/user' } + { input: 'file:///home/user', out: 'https:///home/user' }, + { input: 'foo.bar.com', out: 'https://foo.bar.com' } ] for (const t of tests) {