DEV Community

Cover image for 1 line of code: How to create an URL Slug from a string
martin krause
martin krause

Posted on • Updated on

1 line of code: How to create an URL Slug from a string

 const toURLSlug = str => str.trim().toLowerCase().replace(/[\[\]?.,\/#!$%\^&\*;:{}=\"\-_~()…–—·'’\s]/g, "-").replace(/[\-]{2,}/g, "-").replace(/^[\-]/g, "").replace(/[\-]$/g, "");
Enter fullscreen mode Exit fullscreen mode

Returns the a new string as an URL slug.

Uses space, dot, underscore, dash as delimiters as well as punctation marks. Leading and trailing "-" will be removes .

--

Please note that it's optimised for the standard latin alphabet. While unicode characters are allowed and valid in URL-slugs, they are resolved to their unicode equivalent and thus the URL is not nicely formatted anymore.


The repository & npm package

You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.

The code and the npm package will be updated every time I publish a new article.


Follow me on Twitter: @martinkr and consider to buy me a coffee

Photo by zoo_monkey on Unsplash


Subscribe to the weekly modern frontend development newsletter


Discussion (4)

Collapse
jonrandy profile image
Jon Randy

It's a little simplistic - only handles the latin alphabet, and does not deal with accented letters

Collapse
martinkr profile image
martin krause Author

Hey Jon,

thank you for the time to comment.

What are your concerns about the code? Unicode characters can be part of an url, we're just removing some "unnecessary" characters to shorten the string (:;…?!) and replacing the whitespace with '-' to mach the conventions.

What would be your suggestion to enhance the code?

Cheers!

Collapse
jonrandy profile image
Jon Randy

When you copy a URL containing Unicode characters from the address bar and then, for example, paste it into a chat message - all the unicode characters are now encoded - ruining your nice 'readable' URL.

A lot of the good slug libraries cope with this to varying extents by trying to keep the slug to the standard latin alphabet. Obviously this makes the libraries quite complex as simple character substitutions are not enough when working with languages that use entirely different glyphs (e.g Thai - สวัสดี) - transliteration is required.

Thread Thread
martinkr profile image
martin krause Author

Well, a full fledged library is beyond the scope of "these one line functions" :D I'll add a disclaimer that it should be used with the standard latin alphabet.

Thank you for your time,

Martin