Skip to content

Commit

Permalink
fix(withProtocol): handle input without protocol (resolves #52)
Browse files Browse the repository at this point in the history
side effect: hasProtocol allows [protocol]:$
  • Loading branch information
pi0 committed Mar 31, 2022
1 parent 82170f9 commit 4f66249
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
11 changes: 9 additions & 2 deletions src/utils.ts
Expand Up @@ -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 = /\/$|\/\?/
Expand Down Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions test/utilities.test.ts
Expand Up @@ -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] }
]
Expand Down Expand Up @@ -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) {
Expand All @@ -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) {
Expand Down

0 comments on commit 4f66249

Please sign in to comment.