Skip to content

Commit

Permalink
feat: add encodeURL() (#77)
Browse files Browse the repository at this point in the history
* feat: add encodeURL()

* test: encodeURL()
  • Loading branch information
curbengh authored and tomap committed Sep 3, 2019
1 parent 2ac2ba8 commit 2358028
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/encode_url.js
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;
1 change: 1 addition & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ exports.CacheStream = require('./cache_stream');
exports.camelCaseKeys = require('./camel_case_keys');
exports.Color = require('./color');
exports.createSha1Hash = hash.createSha1Hash;
exports.encodeURL = require('./encode_url');
exports.escapeDiacritic = require('./escape_diacritic');
exports.escapeHTML = require('./escape_html');
exports.escapeRegExp = require('./escape_regexp');
Expand Down
42 changes: 42 additions & 0 deletions test/encode_url.spec.js
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/');
});
});

0 comments on commit 2358028

Please sign in to comment.