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  

Recent Posts

How do I create an engaging and informative online quiz or assessment?

Creating an engaging and informative online quiz or assessment can be a powerful tool for… Read More

1 year ago

What are the most effective methods for managing and reducing work-related stress in the hospitality industry?

Work-related stress is a common issue in the hospitality industry, where employees often face long… Read More

1 year ago

How can I improve my assertiveness and communication skills in a leadership position?

In a leadership position, assertiveness and effective communication skills are crucial for success. Being able… Read More

1 year ago

What are the key elements of a successful employee recognition and rewards program?

Employee recognition and rewards programs play a crucial role in motivating and engaging employees, as… Read More

1 year ago

How do I effectively manage and respond to customer feedback and reviews?

Customer feedback and online reviews play a crucial role in shaping a company's reputation and… Read More

1 year ago

What are the best strategies for effective time management as a stay-at-home parent?

Effective time management is crucial for stay-at-home parents who juggle multiple responsibilities on a daily… Read More

1 year ago