Menu

A Tested JavaScript slugify() Function: Accents, Symbols and Edge Cases
📰

A Tested JavaScript slugify() Function: Accents, Symbols and Edge Cases

DEV Community: javascript·Usman Farooqi·18 days ago
#TpVjWdQS
#devtojavascript#devto#dev#replace#slug
Long article (585 words) — no AI summary yet.
Reading 0:00
15s threshold

Quick answer: normalise the text, strip accent marks, lowercase it, replace everything that is not a letter or digit with one hyphen, and trim the ends. The function below does that and handles the awkward cases. If you only need a slug once, paste your title into the Slug Generator .

The function

const SPECIAL = { "ß" : "ss" , "æ" : "ae" , "œ" : "oe" , "ø" : "o" , "đ" : "d" , "ł" : "l" } ;

function slugify ( input , { separator = "-" , maxLength = 60 } = { } ) { const sep = separator ; let s = String ( input ?? "" ) . normalize ( "NFKD" ) // split letters from accents: e-acute -> e + accent mark . replace ( / [ \ u0300 - \ u036f ] / g , "" ) // drop the accent marks . replace ( / [ ßæœøđł ] / gi , ( c ) => SPECIAL [ c . toLowerCase ( ) ] ) . replace ( /&/ g , " and " ) . toLowerCase ( ) . replace ( / [ ^ a - z0 - 9 ] +/ g , sep ) // anything else becomes one separator . replace ( new RegExp ( `^${sep}+|${sep}+$` , "g" ) , "" ) ; // trim separators if ( s . length > maxLength ) { s = s .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.