From cbb72de41abf1afd01f7234ba0084efbf0adf80a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Mon, 7 Dec 2020 18:04:28 +0100 Subject: [PATCH] feat: add `cleanDoubleSlashes` (#2) --- README.md | 11 +++++++++++ src/index.ts | 4 ++++ test/doubleSlash.test.ts | 17 +++++++++++++++++ test/join.test.ts | 1 + 4 files changed, 33 insertions(+) create mode 100644 test/doubleSlash.test.ts diff --git a/README.md b/README.md index a04bbe71..0006ded0 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,17 @@ Ensures url does not ends with a trailing slash withoutTrailingSlash('/foo/') ``` +### `cleanDoubleSlashes` + +Ensures url does not have double slash (except for protocol) + +```ts +// Result: /foo/bar/ +cleanDoubleSlashes('//foo//bar//') +// Result: http://example.com/analyze/http://localhost:3000/ +cleanDoubleSlashes('http://example.com/analyze//http://localhost:3000//') +``` + ## License MIT. Made with 💖 diff --git a/src/index.ts b/src/index.ts index 462a7aea..a607c914 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,6 +13,10 @@ export function withTrailingSlash (input: string = '/'): string { return input.endsWith('/') ? input : (input + '/') } +export function cleanDoubleSlashes (input: string = '/'): string { + return input.split('://').map(str => str.replace(/\/{2,}/g, '/')).join('://') +} + export function hasProtocol (inputStr: string): boolean { return /\w+:\//.test(inputStr) } diff --git a/test/doubleSlash.test.ts b/test/doubleSlash.test.ts new file mode 100644 index 00000000..a4af3e89 --- /dev/null +++ b/test/doubleSlash.test.ts @@ -0,0 +1,17 @@ +// @ts-nocheck +import { cleanDoubleSlashes } from '../src' + +describe('cleanDoubleSlashes', () => { + const tests = { + '//foo//bar//': '/foo/bar/', + 'http://foo.com//': 'http://foo.com/', + 'http://foo.com/bar//foo/': 'http://foo.com/bar/foo/', + 'http://example.com/analyze//http://localhost:3000//': 'http://example.com/analyze/http://localhost:3000/' + } + + for (const input in tests) { + test(input, () => { + expect(cleanDoubleSlashes(input)).toBe(tests[input]) + }) + } +}) diff --git a/test/join.test.ts b/test/join.test.ts index 80100e70..eb36990b 100644 --- a/test/join.test.ts +++ b/test/join.test.ts @@ -7,6 +7,7 @@ describe('joinURL', () => { { input: ['a'], out: '/a' }, { input: ['a', 'b'], out: '/a/b' }, { input: ['a', 'b/', 'c'], out: '/a/b/c' }, + { input: ['a', 'b/', '/c'], out: '/a/b/c' }, { input: ['/a?foo=bar#123', 'b/', 'c/'], out: '/a/b/c/?foo=bar#123' }, { input: ['http://foo.com', 'a'], out: 'http://foo.com/a' } ]