<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Utility For Web]]></title><description><![CDATA[Utility For Web]]></description><link>https://utilityforweb.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sun, 22 Nov 2026 17:31:45 GMT</lastBuildDate><atom:link href="https://utilityforweb.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to Write a Slugify Function That Doesn’t Break on Real-World Text]]></title><description><![CDATA[Guide to generate clean URL slugs in JS, covering Unicode accents, special characters, length limits, and what to do when a slug comes out empty.]]></description><link>https://utilityforweb.hashnode.dev/how-to-write-a-slugify-function-that-doesn-t-break-on-real-world-text</link><guid isPermaLink="true">https://utilityforweb.hashnode.dev/how-to-write-a-slugify-function-that-doesn-t-break-on-real-world-text</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[webdev]]></category><category><![CDATA[SEO]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[info]]></dc:creator><pubDate>Thu, 12 Nov 2026 11:55:34 GMT</pubDate><content:encoded><![CDATA[<p>Every blog, CMS, and e-commerce site needs URL slugs, and most of us write a quick <code>slugify()</code> once and forget about it. Then a title like "Crème Brûlée &amp; Straße" arrives and the output is garbage.</p>
<p>This post walks through a small slug function, the edge cases that break naive versions, and some design decisions worth making early.</p>
<h2>The naive version</h2>
<pre><code class="language-js">const slugify = (s) =&gt;
  s.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-");
</code></pre>
<p>It works for <code>"Hello World"</code>. It fails in several ways:</p>
<table>
<thead>
<tr>
<th>Input</th>
<th>Naive output</th>
<th>Problem</th>
</tr>
</thead>
<tbody><tr>
<td><code>Crème brûlée</code></td>
<td><code>cr-me-br-l-e</code></td>
<td>Accented letters are deleted, not transliterated</td>
</tr>
<tr>
<td><code>Don't stop</code></td>
<td><code>don-t-stop</code></td>
<td>Apostrophe splits the word</td>
</tr>
<tr>
<td><code>Hello!</code></td>
<td><code>hello-</code></td>
<td>Trailing separator</td>
</tr>
<tr>
<td><code>日本語</code></td>
<td><em>(empty)</em></td>
<td>Nothing left after stripping</td>
</tr>
</tbody></table>
<h2>A sturdier implementation</h2>
<pre><code class="language-js">const SPECIAL = {
  "ß": "ss", "æ": "ae", "œ": "oe",
  "ø": "o", "đ": "d", "ł": "l", "þ": "th",
};

function slugify(input, maxLength = 60) {
  let s = input
    .toLowerCase()
    .replace(/[ßæœøđłþ]/g, (ch) =&gt; SPECIAL[ch])
    .normalize("NFKD")                 // split letters from accents
    .replace(/[\u0300-\u036f]/g, "")   // drop the accent marks
    .replace(/['’]/g, "")              // don't -&gt; dont
    .replace(/&amp;/g, " and ")
    .replace(/[^a-z0-9]+/g, "-")       // collapse everything else
    .replace(/^-+|-+$/g, "");          // trim separators

  if (s.length &gt; maxLength) {
    const next = s[maxLength];
    s = s.slice(0, maxLength);
    // avoid cutting a word in half
    if (next &amp;&amp; next !== "-" &amp;&amp; s.includes("-")) {
      s = s.slice(0, s.lastIndexOf("-"));
    }
    s = s.replace(/-+$/, "");
  }
  return s;
}
</code></pre>
<p>Test it:</p>
<pre><code class="language-js">slugify("Crème Brûlée &amp; Straße"); // "creme-brulee-and-strasse"
slugify("  #Utility$ For% Web! is Awesome. ");
// "utility-for-web-is-awesome"
slugify("Don’t Stop");            // "dont-stop"
</code></pre>
<h3>Why these steps matter</h3>
<ul>
<li><code>normalize("NFKD")</code> decomposes <code>é</code> into <code>e</code> plus a combining accent, so the second <code>replace</code> can remove just the accent.</li>
<li><strong>The</strong> <code>SPECIAL</code> <strong>map</strong> exists because letters like <code>ß</code> and <code>ø</code> don't decompose under Unicode normalization. They need explicit rules.</li>
<li><strong>Removing apostrophes before collapsing</strong> keeps <code>dont</code> as one word instead of <code>don-t</code>.</li>
<li><strong>Collapsing runs of symbols</strong> prevents <code>--</code> in the middle.</li>
<li><strong>Cutting at a word boundary</strong> gives <code>how-to-build-a-url</code> instead of <code>how-to-build-a-ur</code>.</li>
</ul>
<h2>Edge cases to decide on early</h2>
<p><strong>1. Empty results.</strong> A title in a non-Latin script produces an empty slug with the code above. Options: keep Unicode in the slug (modern browsers and search engines handle it, though copy-pasted URLs get percent-encoded), transliterate with a library, or fall back to an ID such as <code>post-1234</code>. Pick one deliberately.</p>
<p><strong>2. Uniqueness.</strong> Two posts titled "Introduction" collide. Check the database and append a suffix (<code>introduction-2</code>), or include the ID.</p>
<p><strong>3. Stop words.</strong> Removing words like "the" and "of" shortens URLs, but it can change meaning (<code>to-be-or-not-to-be</code> becomes <code>be-not-be</code>). Make it optional rather than the default.</p>
<p><strong>4. Hyphens, not underscores.</strong> Google's documentation recommends hyphens as word separators, so use <code>-</code>.</p>
<p><strong>5. Changing slugs later.</strong> Once a URL is public and linked, changing its slug breaks inbound links. If you must change it, add a 301 redirect from the old slug to the new one. This is a good reason to avoid putting dates or numbers in slugs that you may update (<code>5-tips-for-x</code> becomes wrong when you add a sixth tip).</p>
<h2>Going the other way: slug to title</h2>
<p>Sometimes you need to turn a slug back into a readable label, for breadcrumbs or admin lists:</p>
<pre><code class="language-js">const unslugify = (slug) =&gt;
  slug
    .split("-")
    .map((w) =&gt; w.charAt(0).toUpperCase() + w.slice(1))
    .join(" ");

unslugify("utility-for-web-is-awesome"); // "Utility For Web Is Awesome"
</code></pre>
<p>This is lossy by nature. Acronyms (<code>api</code>), brand casing (<code>iPhone</code>), and lowercase connecting words can't be recovered, so don't treat it as an inverse of <code>slugify()</code>.</p>
<h2>A quick tool, in case you don't need code</h2>
<p>Disclosure: I run a small collection of free browser utilities. If you just need to slugify a title once, or convert a slug back to title case, there's a free one here: <a href="https://www.utilityforweb.com/text-to-slug/">Text to Slug</a>. It follows the basic steps above (lowercase, trim, strip special characters, hyphenate) plus the reverse conversion. It's meant for quick one-off use. For anything automated, use a function like the one in this post.</p>
<h2>Summary</h2>
<ul>
<li>Normalize Unicode before stripping characters.</li>
<li>Handle letters that don't decompose (<code>ß</code>, <code>ø</code>, <code>æ</code>).</li>
<li>Plan for empty results, collisions, and length limits.</li>
<li>Treat published slugs as permanent, and redirect if you change them.</li>
</ul>
<p>What edge cases have you hit? Let me know in the comments.</p>
]]></content:encoded></item></channel></rss>