Add URLJoin.md
This commit is contained in:
20
snippets/URLJoin.md
Normal file
20
snippets/URLJoin.md
Normal file
@ -0,0 +1,20 @@
|
||||
### URLJoin
|
||||
|
||||
Joins all given URL segments together, then normalizes the resulting URL.
|
||||
|
||||
Use `String.join('/')` to combine URL segments, then a series of `String.replace()` calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with `'&'` and normalize first parameter delimiter).
|
||||
|
||||
```js
|
||||
const URLJoin = (...args) =>
|
||||
args.join('/')
|
||||
.replace(/[\/]+/g,'/')
|
||||
.replace(/^(.+):\//,'$1://')
|
||||
.replace(/^file:/,'file:/')
|
||||
.replace(/\/(\?|&|#[^!])/g, '$1')
|
||||
.replace(/\?/g,'&')
|
||||
.replace('&','?');
|
||||
```
|
||||
|
||||
```js
|
||||
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); // 'http://www.google.com/a/b/cd?foo=123&bar=foo'
|
||||
```
|
||||
Reference in New Issue
Block a user