-
-
Notifications
You must be signed in to change notification settings - Fork 59
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* feat: add encodeURL() * test: encodeURL()
- Loading branch information
Showing
3 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
'use strict'; | ||
|
||
const { parse, format } = require('url'); | ||
|
||
function encodeURL(str) { | ||
if (parse(str).protocol) { | ||
return format({ | ||
protocol: parse(str).protocol, | ||
hostname: parse(str).hostname, | ||
pathname: encodeURI(decodeURI(parse(str).pathname)) | ||
}); | ||
} | ||
|
||
return encodeURI(str); | ||
} | ||
|
||
module.exports = encodeURL; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
'use strict'; | ||
|
||
require('chai').should(); | ||
|
||
describe('encodeURL', () => { | ||
const encodeURL = require('../lib/encode_url'); | ||
|
||
it('regular', () => { | ||
const content = 'http://foo.com/'; | ||
encodeURL(content).should.eql(content); | ||
}); | ||
|
||
it('space', () => { | ||
const content = 'http://foo.com/bar baz'; | ||
encodeURL(content).should.eql('http://foo.com/bar%20baz'); | ||
}); | ||
|
||
it('unicode', () => { | ||
const content = 'http://foo.com/bár'; | ||
encodeURL(content).should.eql('http://foo.com/b%C3%A1r'); | ||
}); | ||
|
||
it('idn', () => { | ||
const content = 'http://bár.com/baz'; | ||
encodeURL(content).should.eql('http://xn--br-mia.com/baz'); | ||
}); | ||
|
||
it('path', () => { | ||
const content = '/foo/bar/'; | ||
encodeURL(content).should.eql(content); | ||
}); | ||
|
||
it('path with space', () => { | ||
const content = '/foo bar/baz/'; | ||
encodeURL(content).should.eql('/foo%20bar/baz/'); | ||
}); | ||
|
||
it('path with unicode', () => { | ||
const content = '/foo/bár/'; | ||
encodeURL(content).should.eql('/foo/b%C3%A1r/'); | ||
}); | ||
}); |