Skip to content

Commit 0ee9d94

Browse files
authored
Improve stripWWW logic (#117)
1 parent 14b79c6 commit 0ee9d94

2 files changed

Lines changed: 11 additions & 3 deletions

File tree

index.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -147,10 +147,11 @@ const normalizeUrl = (urlString, options) => {
147147
urlObj.hostname = urlObj.hostname.replace(/\.$/, '');
148148

149149
// Remove `www.`
150-
if (options.stripWWW && /^www\.(?:[a-z\-\d]{2,63})\.(?:[a-z.]{2,5})$/.test(urlObj.hostname)) {
151-
// Each label should be max 63 at length (min: 2).
152-
// The extension should be max 5 at length (min: 2).
150+
if (options.stripWWW && /^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(urlObj.hostname)) {
151+
// Each label should be max 63 at length (min: 1).
153152
// Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
153+
// Each TLD should be up to 63 characters long (min: 2).
154+
// It is technically possible to have a single character TLD, but none currently exist.
154155
urlObj.hostname = urlObj.hostname.replace(/^www\./, '');
155156
}
156157
}

test.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,13 @@ test('stripWWW option', t => {
7575
t.is(normalizeUrl('www.sindresorhus.com', options), 'http://www.sindresorhus.com');
7676
t.is(normalizeUrl('http://www.êxample.com', options), 'http://www.xn--xample-hva.com');
7777
t.is(normalizeUrl('sindre://www.sorhus.com', options), 'sindre://www.sorhus.com');
78+
79+
const options2 = {stripWWW: true};
80+
t.is(normalizeUrl('http://www.vue.amsterdam', options2), 'http://vue.amsterdam');
81+
t.is(normalizeUrl('http://www.sorhus.xx--bck1b9a5dre4c', options2), 'http://sorhus.xx--bck1b9a5dre4c');
82+
83+
const tooLongTLDURL = 'http://www.sorhus.' + ''.padEnd(64, 'a');
84+
t.is(normalizeUrl(tooLongTLDURL, options2), tooLongTLDURL);
7885
});
7986

8087
test('removeQueryParameters option', t => {

0 commit comments

Comments
 (0)