Add URLJoin.md

This commit is contained in:
Angelos Chalaris
2018-01-16 15:53:03 +02:00
parent 498d8fa16b
commit daedf4c8e0
5 changed files with 574 additions and 524 deletions

20
snippets/URLJoin.md Normal file
View 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'
```

View File

@ -193,6 +193,7 @@ truthCheckCollection:object,logic,array
unescapeHTML:string,browser
union:array,math
untildify:node,string
URLJoin:string,utility,regexp
UUIDGeneratorBrowser:browser,utility,random
UUIDGeneratorNode:node,utility,random
validateNumber:utility,math

8
test/URLJoin/URLJoin.js Normal file
View File

@ -0,0 +1,8 @@
module.exports = URLJoin = (...args) =>
args.join('/')
.replace(/[\/]+/g,'/')
.replace(/^(.+):\//,'$1://')
.replace(/^file:/,'file:/')
.replace(/\/(\?|&|#[^!])/g, '$1')
.replace(/\?/g,'&')
.replace('&','?');

View File

@ -0,0 +1,15 @@
const test = require('tape');
const URLJoin = require('./URLJoin.js');
test('Testing URLJoin', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof URLJoin === 'function', 'URLJoin is a Function');
t.equal(URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'), 'http://www.google.com/a/b/cd?foo=123&bar=foo', 'Returns proper URL');
t.equal(URLJoin('file://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'), 'file:///www.google.com/a/b/cd?foo=123&bar=foo', 'Returns proper URL');
//t.deepEqual(URLJoin(args..), 'Expected');
//t.equal(URLJoin(args..), 'Expected');
//t.false(URLJoin(args..), 'Expected');
//t.throws(URLJoin(args..), 'Expected');
t.end();
});

File diff suppressed because it is too large Load Diff