How to convert string in to slug using JavaScript

How to convert string in to slug using JavaScript

Today we are going to learn how to convert string to slug using JavaScript. We will write a custom JavaScript function called “convertToSlug” and it makes our string as a slug value. I’m sure enough, it will be a fun to create slug in JavaScript. Have a look at code snippet-

/*****************************************************
 *@Description: Convert any string in to slug URL.
 *@Parameters: A text and a delimiter
 *****************************************************/
function convertToSlug(Text,Delimiter) {

    if(Delimiter == null) {
        Delimiter = "-";
    }

    var new_text= Text
            .toLowerCase()            
            .replace(/ +/g,Delimiter);

   var r = new_text;

        r = r.replace(new RegExp("\\s", 'g'),"");
        r = r.replace(new RegExp("[àáâãäå]", 'g'),"a");
        r = r.replace(new RegExp("æ", 'g'),"ae");
        r = r.replace(new RegExp("ç", 'g'),"c");
        r = r.replace(new RegExp("[èéêë]", 'g'),"e");
        r = r.replace(new RegExp("[ìíîï]", 'g'),"i");
        r = r.replace(new RegExp("ñ", 'g'),"n");                            
        r = r.replace(new RegExp("[òóôõö]", 'g'),"o");
        r = r.replace(new RegExp("œ", 'g'),"oe");
        r = r.replace(new RegExp("[ùúûü]", 'g'),"u");
        r = r.replace(new RegExp("[ýÿ]", 'g'),"y");
        r = r.replace(new RegExp("\\W", 'g'),"");

    return r; 

}

So, we have created a function called convertToSlug and it’s contain 2 parameter. First parameter will be your string and second parameter will be the delimiter. Second parameter is optional. By default it replace “space” of a character by “hyphen”. But you can easily change it and add “underscore” character instead of default “hyphen”. Very simple. Now, it’s time to call the function.

– Call The function:

We are going to call this function like other JavaScript function.

var my_string = "hello world";

var my_slug = convertToSlug(my_string); //return hello-world

var my_slug_2 = convertToSlug(my_string, "_"); //return hello_world

Enjoy!

Share It

Related Posts