From 191ad4ba1618dfdcab4273703761b7306265436e Mon Sep 17 00:00:00 2001 From: Jignesh Kakadiya Date: Tue, 18 Dec 2018 20:59:45 +0530 Subject: [PATCH] Fix incorrect removal of trailing slash from a hash (#82) --- index.js | 6 +++++- test.js | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 7e9e294..5853ebd 100644 --- a/index.js +++ b/index.js @@ -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(/\/$/, ''); } diff --git a/test.js b/test.js index 9333d35..462fc34 100644 --- a/test.js +++ b/test.js @@ -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 => { @@ -151,6 +152,8 @@ 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, @@ -158,6 +161,7 @@ test('removeTrailingSlash and removeDirectoryIndex options)', t => { }; 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 => {