Skip to content

Commit

Permalink
Merge e14f8e0 into 4f07d2b
Browse files Browse the repository at this point in the history
  • Loading branch information
tomap committed Nov 2, 2019
2 parents 4f07d2b + e14f8e0 commit 924c354
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 6 deletions.
5 changes: 1 addition & 4 deletions README.md
Expand Up @@ -113,15 +113,12 @@ decodeURI(format(new URL('http://xn--br-mia.com.com/b%C3%A1r'), {unicode: true})

### encodeURL(str)

Encode URL or path into a [safe format](https://en.wikipedia.org/wiki/Percent-encoding). Domain is encoded into [punycode](https://en.wikipedia.org/wiki/Punycode) when necessary.
Encode URL or path into a [safe format](https://en.wikipedia.org/wiki/Percent-encoding).

``` js
encodeURL('http://foo.com/bár')
// http://foo.com/b%C3%A1r

encodeURL('http://bár.com/baz')
// http://xn--br-mia.com/baz

encodeURL('/foo/bár/')
// /foo/b%C3%A1r/
```
Expand Down
5 changes: 4 additions & 1 deletion lib/encode_url.js
@@ -1,5 +1,6 @@
'use strict';

const { toUnicode } = require('./punycode');
const { URL } = require('url');

const urlObj = (str) => {
Expand All @@ -24,7 +25,9 @@ const encodeURL = (str) => {
if (parsed.origin === 'null') return str;

parsed.search = encodeURI(safeDecodeURI(parsed.search));
return parsed.toString();
// preserve IDN
// TODO: refactor to url.format() once Node 8 EOL
return parsed.toString().replace(parsed.hostname, toUnicode(parsed.hostname));
}

return encodeURI(safeDecodeURI(str));
Expand Down
7 changes: 6 additions & 1 deletion test/encode_url.spec.js
Expand Up @@ -67,7 +67,12 @@ describe('encodeURL', () => {

it('idn', () => {
const content = 'http://bár.com/baz';
encodeURL(content).should.eql('http://xn--br-mia.com/baz');
encodeURL(content).should.eql('http://bár.com/baz');
});

it('idn - punycode', () => {
const content = 'http://xn--br-mia.com/baz';
encodeURL(content).should.eql('http://bár.com/baz');
});

it('path', () => {
Expand Down

0 comments on commit 924c354

Please sign in to comment.