Skip to content

Commit

Permalink
Improve stripWWW logic (#117)
Browse files Browse the repository at this point in the history
  • Loading branch information
gcox authored Aug 2, 2020
1 parent 14b79c6 commit 0ee9d94
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
7 changes: 4 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,11 @@ const normalizeUrl = (urlString, options) => {
urlObj.hostname = urlObj.hostname.replace(/\.$/, '');

// Remove `www.`
if (options.stripWWW && /^www\.(?:[a-z\-\d]{2,63})\.(?:[a-z.]{2,5})$/.test(urlObj.hostname)) {
// Each label should be max 63 at length (min: 2).
// The extension should be max 5 at length (min: 2).
if (options.stripWWW && /^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(urlObj.hostname)) {
// Each label should be max 63 at length (min: 1).
// Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
// Each TLD should be up to 63 characters long (min: 2).
// It is technically possible to have a single character TLD, but none currently exist.
urlObj.hostname = urlObj.hostname.replace(/^www\./, '');
}
}
Expand Down
7 changes: 7 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,13 @@ test('stripWWW option', t => {
t.is(normalizeUrl('www.sindresorhus.com', options), 'http://www.sindresorhus.com');
t.is(normalizeUrl('http://www.êxample.com', options), 'http://www.xn--xample-hva.com');
t.is(normalizeUrl('sindre://www.sorhus.com', options), 'sindre://www.sorhus.com');

const options2 = {stripWWW: true};
t.is(normalizeUrl('http://www.vue.amsterdam', options2), 'http://vue.amsterdam');
t.is(normalizeUrl('http://www.sorhus.xx--bck1b9a5dre4c', options2), 'http://sorhus.xx--bck1b9a5dre4c');

const tooLongTLDURL = 'http://www.sorhus.' + ''.padEnd(64, 'a');
t.is(normalizeUrl(tooLongTLDURL, options2), tooLongTLDURL);
});

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

0 comments on commit 0ee9d94

Please sign in to comment.