Skip to content

Commit

Permalink
Fix incorrect removal of trailing slash from a hash (#82)
Browse files Browse the repository at this point in the history
  • Loading branch information
bitshadow authored and sindresorhus committed Dec 18, 2018
1 parent e02a3aa commit 191ad4b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 5 additions & 1 deletion index.js
Expand Up @@ -129,11 +129,15 @@ module.exports = (urlString, options) => {
urlObj.searchParams.sort();
}

if (options.removeTrailingSlash) {
urlObj.pathname = urlObj.pathname.replace(/\/$/, '');
}

// Take advantage of many of the Node `url` normalizations
urlString = urlObj.toString();

// Remove ending `/`
if (options.removeTrailingSlash || urlObj.pathname === '/') {
if ((options.removeTrailingSlash || urlObj.pathname === '/') && urlObj.hash === '') {
urlString = urlString.replace(/\/$/, '');
}

Expand Down
4 changes: 4 additions & 0 deletions test.js
Expand Up @@ -115,6 +115,7 @@ test('removeTrailingSlash option', t => {
t.is(normalizeUrl('http://sindresorhus.com/', options), 'http://sindresorhus.com');
t.is(normalizeUrl('http://sindresorhus.com/redirect/'), 'http://sindresorhus.com/redirect');
t.is(normalizeUrl('http://sindresorhus.com/redirect/', options), 'http://sindresorhus.com/redirect/');
t.is(normalizeUrl('http://sindresorhus.com/#/', options), 'http://sindresorhus.com/#/');
});

test('removeDirectoryIndex option', t => {
Expand Down Expand Up @@ -151,13 +152,16 @@ test('removeTrailingSlash and removeDirectoryIndex options)', t => {
};
t.is(normalizeUrl('http://sindresorhus.com/path/', options1), 'http://sindresorhus.com/path');
t.is(normalizeUrl('http://sindresorhus.com/path/index.html', options1), 'http://sindresorhus.com/path');
t.is(normalizeUrl('http://sindresorhus.com/#/path/', options1), 'http://sindresorhus.com/#/path/');
t.is(normalizeUrl('http://sindresorhus.com/foo/#/bar/', options1), 'http://sindresorhus.com/foo#/bar/');

const options2 = {
removeTrailingSlash: false,
removeDirectoryIndex: true
};
t.is(normalizeUrl('http://sindresorhus.com/path/', options2), 'http://sindresorhus.com/path/');
t.is(normalizeUrl('http://sindresorhus.com/path/index.html', options2), 'http://sindresorhus.com/path/');
t.is(normalizeUrl('http://sindresorhus.com/#/path/', options2), 'http://sindresorhus.com/#/path/');
});

test('sortQueryParameters option', t => {
Expand Down

0 comments on commit 191ad4b

Please sign in to comment.