Skip to content

Commit

Permalink
[fix] prepend slash to pathname if it is missing
Browse files Browse the repository at this point in the history
  • Loading branch information
Swaagie committed Oct 6, 2016
1 parent b3ad2f7 commit 33f7686
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 34 deletions.
86 changes: 52 additions & 34 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -240,43 +240,61 @@ function URL(address, location, parser) {
*/
URL.prototype.set = function set(part, value, fn) {
var url = this;

switch(part) {
case 'query':
if ('string' === typeof value && value.length) {
value = (fn || qs.parse)(value);
}

if ('query' === part) {
if ('string' === typeof value && value.length) {
value = (fn || qs.parse)(value);
}
url[part] = value;
break;

url[part] = value;
} else if ('port' === part) {
url[part] = value;
case 'port':
url[part] = value;

if (!required(value, url.protocol)) {
url.host = url.hostname;
url[part] = '';
} else if (value) {
url.host = url.hostname +':'+ value;
}
} else if ('hostname' === part) {
url[part] = value;

if (url.port) value += ':'+ url.port;
url.host = value;
} else if ('host' === part) {
url[part] = value;

if (/:\d+$/.test(value)) {
value = value.split(':');
url.port = value.pop();
url.hostname = value.join(':');
} else {
url.hostname = value;
url.port = '';
}
} else if ('protocol' === part) {
url.protocol = value.toLowerCase();
url.slashes = !fn;
} else {
url[part] = value;
if (!required(value, url.protocol)) {
url.host = url.hostname;
url[part] = '';
} else if (value) {
url.host = url.hostname +':'+ value;
}

break;

case 'hostname':
url[part] = value;

if (url.port) value += ':'+ url.port;
url.host = value;
break;

case 'host':
url[part] = value;

if (/:\d+$/.test(value)) {
value = value.split(':');
url.port = value.pop();
url.hostname = value.join(':');
} else {
url.hostname = value;
url.port = '';
}

break;

case 'protocol':
url.protocol = value.toLowerCase();
url.slashes = !fn;
break;

case 'pathname':
url.pathname = value.charAt(0) === '/' ? value : '/' + value;
break;

default:
url[part] = value;
break;
}

for (var i = 0; i < rules.length; i++) {
Expand Down
10 changes: 10 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,16 @@ describe('url-parse', function () {
assume(parsed.href).equals('http://example.com/');
});

it('prepends / to pathname', function () {
var url = parse();

url.set('host', 'example.com:80').set('pathname', 'will/get/slash/prepended');

assume(url.pathname).equals('/will/get/slash/prepended');
assume(url.href).equals('example.com:80/will/get/slash/prepended')

});

it('does not care about spaces', function () {
var url = 'http://x.com/path?that\'s#all, folks'
, parsed = parse(url);
Expand Down

0 comments on commit 33f7686

Please sign in to comment.