How to convert any text to slug with JavaScript?

Probably you are here to find a way to convert your text string in to a slug. Me too wanted the same and could create the following quick and neat function after reading couple of resources.
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 url.
can-you-convert-me-to-a-slug

Hope this helped :) 

No comments:

Post a Comment