Skip to content

Commit

Permalink
simplify normalize function
Browse files Browse the repository at this point in the history
replace normalize function to only use 3 replace rules instead of 6
  • Loading branch information
rauberdaniel committed Mar 18, 2016
1 parent baac627 commit d6886a3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
20 changes: 12 additions & 8 deletions lib/url-join.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@
else context[name] = definition();
})('urljoin', this, function () {

function normalize (str) {
return str
.replace(/^\/\//g, '://') // replace leading // with :/
.replace(/[\/]+/g, '/') // flatten multiple occurencies of / to single /
.replace(/\/\?/g, '?') // remove trailing / before parameters
.replace(/\/\#/g, '#') // remove trailing / before hash
.replace(/\:\//g, '://') // replace :/ with ://
.replace(/^:\/\//g , '//'); // replace leading :// with //
function normalize (str, options) {

// make sure protocol is followed by two slashes
str = str.replace(/:\//g, '://');

// remove consecutive slashes
str = str.replace(/([^:\s])\/+/g, '$1/');

// remove trailing slash before parameters or hash
str = str.replace(/\/(\?|#)/g, '$1');

return str;
}

return function () {
Expand Down
9 changes: 7 additions & 2 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ describe('url join', function () {
.should.eql('http://www.google.com/foo/bar?test=123');
});

it('should be able to join protocol with slashes', function () {
urljoin('http://', 'www.google.com/', 'foo/bar', '?test=123')
.should.eql('http://www.google.com/foo/bar?test=123');
});

it('should remove extra slashes', function () {
urljoin('http:', 'www.google.com///', 'foo/bar', '?test=123')
.should.eql('http://www.google.com/foo/bar?test=123');
Expand All @@ -21,8 +26,8 @@ describe('url join', function () {
.should.eql('http://www.google.com/foo/bar?test=123#faaaaa');
});

it('should keep leading //', function () {
it('should support protocol-relative urls', function () {
urljoin('//www.google.com', 'foo/bar', '?test=123')
.should.eql('//www.google.com/foo/bar?test=123')
})
});
});

0 comments on commit d6886a3

Please sign in to comment.