Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
url: make url.format escape delimiters in path and query
Browse files Browse the repository at this point in the history
`url.format` should escape ? and # chars in pathname, and # chars in
search, because they change the semantics of the operation otherwise.
Don't escape % chars, or anything else. (see: #4082)
  • Loading branch information
coltrane authored and isaacs committed Oct 30, 2012
1 parent 19b87bb commit 54d293d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/url.js
Expand Up @@ -390,6 +390,11 @@ Url.prototype.format = function() {
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
if (search && search.charAt(0) !== '?') search = '?' + search;

pathname = pathname.replace(/[?#]/g, function(match) {
return encodeURIComponent(match);
});
search = search.replace('#', '%23');

return protocol + host + pathname + search + hash;
};

Expand Down
44 changes: 44 additions & 0 deletions test/simple/test-url.js
Expand Up @@ -943,6 +943,50 @@ var formatTests = {
'protocol': 'coap',
'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616',
'pathname': '/s/stopButton'
},

// encode context-specific delimiters in path and query, but do not touch
// other non-delimiter chars like `%`.
// <https://github.com/joyent/node/issues/4082>

// `#`,`?` in path
'/path/to/%%23%3F+=&.txt?foo=theA1#bar' : {
href : '/path/to/%%23%3F+=&.txt?foo=theA1#bar',
pathname: '/path/to/%#?+=&.txt',
query: {
foo: 'theA1'
},
hash: "#bar"
},

// `#`,`?` in path + `#` in query
'/path/to/%%23%3F+=&.txt?foo=the%231#bar' : {
href : '/path/to/%%23%3F+=&.txt?foo=the%231#bar',
pathname: '/path/to/%#?+=&.txt',
query: {
foo: 'the#1'
},
hash: "#bar"
},

// `?` and `#` in path and search
'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag': {
href: 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag',
protocol: 'http:',
hostname: 'ex.com',
hash: '#frag',
search: '?abc=the#1?&foo=bar',
pathname: '/foo?100%m#r',
},

// `?` and `#` in search only
'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag': {
href: 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag',
protocol: 'http:',
hostname: 'ex.com',
hash: '#frag',
search: '?abc=the#1?&foo=bar',
pathname: '/fooA100%mBr',
}
};
for (var u in formatTests) {
Expand Down

0 comments on commit 54d293d

Please sign in to comment.