JavaScriptFundamental (ES6), part 2
URL slug generator with accent folding in JavaScript
97 A slug generator, and what to do when it comes out empty
easyTurn a title into a URL slug: fold accents away, lower-case it, collapse every run of punctuation into a single hyphen, and trim the hyphens off both ends. Cap the length without cutting a word in half. Then make it unique against slugs already taken, and be honest about the inputs that produce nothing at all.
Stuck? Three hints, smallest first
- 1.
normalize('NFD')splits an accented letter into a letter and a mark; deleting\p{Diacritic}leaves the letter. - 2. One
replace(/[^a-z0-9]+/g, '-')handles spaces, punctuation and runs of both in a single pass. - 3. To cap without cutting a word, slice one character past the limit and cut back to the last hyphen.
function slugify(text, max = 60) {
const base = text
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '') // fold the accents off
.toLowerCase()
.replace(/['\u2019]/g, '') // an apostrophe disappears rather than becoming a hyphen
.replace(/[^a-z0-9]+/g, '-') // everything else collapses to one hyphen
.replace(/^-+|-+$/g, '');
if (base.length <= max) return base;
const oneOver = base.slice(0, max + 1); // one character past, to see if we cut a word
const lastHyphen = oneOver.lastIndexOf('-');
const cut = lastHyphen > 0 ? oneOver.slice(0, lastHyphen) : oneOver.slice(0, max);
return cut.replace(/-+$/, '');
}
function uniqueSlug(base, taken) {
if (base === '') return '';
if (!taken.has(base)) return base;
let n = 2;
while (taken.has(base + '-' + n)) n += 1;
return base + '-' + n;
}
const plain = slugify('Lagos Island Market');
const accented = slugify('Ọlámidé Adéyemi');
const punctuated = slugify('Lagos --- Ibadan!!! Express');
const edges = slugify(' ¡Hola, Naija! ');
const apostrophe = slugify("Chief's Bar & Grill");
const longTitle = 'Ikeja City Mall, Alausa, Ikeja, Lagos State, Nigeria';
const cappedAt40 = slugify(longTitle, 40);
const cappedAt30 = slugify(longTitle, 30);
const punctuationOnly = slugify('!!! ---');
const otherScript = slugify('文章');
const taken = new Set(['lagos-island-market', 'lagos-island-market-2']);
const firstFree = uniqueSlug(plain, taken);
const noneTaken = uniqueSlug('yaba-market', taken);
console.log('accented :', accented);
console.log('punctuated :', punctuated, '|', edges, '|', apostrophe);
console.log('capped :', cappedAt40, '(' + cappedAt40.length + ')');
console.log('unique :', firstFree);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('spaces become single hyphens and everything is lower case', plain, 'lagos-island-market');
test('accents and the Yoruba dot below are folded to plain letters', accented, 'olamide-adeyemi');
test('a run of punctuation collapses to one hyphen, never two', punctuated, 'lagos-ibadan-express');
test('leading and trailing junk is trimmed off both ends', edges, 'hola-naija');
test('an apostrophe is deleted rather than becoming a hyphen', apostrophe, 'chiefs-bar-grill');
test('the cap cuts back to a word boundary and never leaves a trailing hyphen', [cappedAt40, cappedAt40.length, cappedAt30], ['ikeja-city-mall-alausa-ikeja-lagos-state', 40, 'ikeja-city-mall-alausa-ikeja']);
test('punctuation alone, or a script with no Latin letters, slugs to nothing at all', [punctuationOnly, otherScript], ['', '']);
test('and a taken slug gets the first free suffix, while a free one is left alone', [firstFree, noneTaken], ['lagos-island-market-3', 'yaba-market']);
normalize('NFD') then deleting \p{Diacritic} is the whole accent-folding trick: NFD splits é into e plus a combining acute, and the mark is what gets deleted. It handles the Yoruba ọ too, because the dot below is a combining mark like any other. What it does not handle is a letter that has no decomposition — ø, ß, đ, ł stay exactly as they are and then get replaced by a hyphen, so a name in one of those alphabets needs an explicit lookup table. Exercise 98 has the collation version of this problem.
Order matters in that chain. Folding before lower-casing, and collapsing runs with + rather than one character at a time, is what stops lagos---ibadan becoming lagos-----ibadan. Trimming the ends last is required because the collapse itself creates the leading and trailing hyphens.
The seventh assertion is the case that reaches production as a broken URL. A title made entirely of punctuation, or written in a script with no Latin letters at all, slugs to the empty string — and /vendors/ is not a page. Anything generating slugs from user input needs a fallback: the record id, a transliteration library, or a rejection at the form. And the eighth assertion is why the suffix search starts at 2 and walks up: the first collision is -2, not -1, and -2 may itself be taken.