Skip to content

Commit

Permalink
feat: add cleanDoubleSlashes (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
atinux authored Dec 7, 2020
1 parent 96a91be commit cbb72de
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 💖
Expand Down
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
17 changes: 17 additions & 0 deletions test/doubleSlash.test.ts
Original file line number Diff line number Diff line change
@@ -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])
})
}
})
1 change: 1 addition & 0 deletions test/join.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' }
]
Expand Down

0 comments on commit cbb72de

Please sign in to comment.