Skip to content

Commit

Permalink
fix: split logic for files
Browse files Browse the repository at this point in the history
  • Loading branch information
xtuc committed Apr 10, 2017
1 parent 48ebe0d commit d7053a9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 10 deletions.
23 changes: 17 additions & 6 deletions lib/url-join.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,27 @@
else context[name] = definition();
})('urljoin', this, function () {

if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position){
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}

function normalize (str, options) {

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

// remove consecutive slashes
str = str.replace(/([^:\s])\/+/g, '$1/');
// make sure file protocol has max three slashes
str = str.replace(/(\/{0,3})\/*/g, '$1');
} else {

// set file:// for file protocol
str = str.replace(/(file:)\/+/g, '$1///');
// 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');
Expand Down
16 changes: 12 additions & 4 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,24 @@ describe('url join', function () {
});

it('should support file protocol urls', function () {
urljoin('file:', 'android_asset', 'foo/bar')
.should.eql('file:///android_asset/foo/bar')
urljoin('file:/', 'android_asset', 'foo/bar')
.should.eql('file://android_asset/foo/bar')

urljoin('file:', '/android_asset', 'foo/bar')
.should.eql('file://android_asset/foo/bar')
});

it('should support absolute file protocol urls', function () {
urljoin('file:', '///android_asset', 'foo/bar')
.should.eql('file:///android_asset/foo/bar')

urljoin('file:', '/android_asset', 'foo/bar')
urljoin('file:///', 'android_asset', 'foo/bar')
.should.eql('file:///android_asset/foo/bar')

urljoin('file:///', 'android_asset', 'foo/bar')
urljoin('file:///', '//android_asset', 'foo/bar')
.should.eql('file:///android_asset/foo/bar')

urljoin('file:///android_asset', 'foo/bar')
.should.eql('file:///android_asset/foo/bar')
});

Expand Down

0 comments on commit d7053a9

Please sign in to comment.