Browse files

url: make url.format escape delimiters in path and query

`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...
1 parent 19b87bb commit 54d293da560a86e48b302c0ef219ac6e38a9a1e9 @coltrane coltrane committed with isaacs Oct 15, 2012
Showing with 49 additions and 0 deletions.
  1. +5 −0 lib/url.js
  2. +44 −0 test/simple/test-url.js
View
5 lib/url.js
@@ -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;
};
View
44 test/simple/test-url.js
@@ -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) {

0 comments on commit 54d293d

Please sign in to comment.