How to easily convert any string/text to URL(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 :)  

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: