How to convert any text to an SEO friendly slug with JavaScript?
Probably you are here to find a way to convert your text string into a slug. Me too wanted the same and could create the following quick and neat function after reading a couple of resources.
I find the below clean and foolproof function works well when converting any text string to an SEO friendly slug.
function makeSlug(String) {
return String
.toLowerCase() //Convert the whole string to lowercase
.replace(/[^\w ]+/g,'') //Remove all the non-word characters
.replace(/ +/g,'-') //Replace white spaces with hyphens
.replace(/^-/g,'') //Remove leading hyphens (caused by leading spaces)
.replace(/-$/g,'') //Remove trailing hyphens (caused by trailing spaces)
}
Then you can call the function with the text as your parameter.
var text = "Can you convert me to a slug?"
var slug = makeSlug(text);
And the result will be a hyphen separated, clean, SEO friendly slug.
can-you-convert-me-to-a-slug
Don't forget to leave a comment if this was helpful 😊
Comments