Slugify a string in JavaScript
By Flavio Copes
Learn how to turn a string into a lowercase URL slug in JavaScript with the slugify package, including strict punctuation removal.
~~~
Install the slugify library
npm i slugify
Then import it
import slugify from 'slugify'
and you can do
const slug = slugify('Testing this', {
lower: true,
strict: true
})
console.log(slug) // testing-this
lower converts the result to lowercase. strict removes characters other than letters, numbers, and the replacement character.
You can also provide a remove regular expression when you need a custom rule:
slugify('Testing. this!', {
lower: true,
remove: /[*+~.,()'"!:@]/g
})
Slug generation is usually part of a URL contract. Decide what should happen with duplicate slugs and avoid changing the algorithm after publishing URLs unless you also add redirects.
If you just need to slugify a string once, without writing any code, use my slug generator tool.
~~~
Related posts about js: