How to convert string into a slug using JavaScript

How to convert string in to slug using JavaScript

Today we are going to learn how to convert a string into a slug using JavaScript. We will write a custom JavaScript function called convertToSlug and it generates the string into a slug value.

Here goes the full snippets.

/*****************************************************
 *@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; 

}

We have created a function called convertToSlug and it contains two parameter. First parameter will be a string and second parameter will be the delimiter. Second parameter is optional. By default the function replaces all the “space” by “hyphen“. However, you can change it and add “underscore” character instead of default “hyphen“. Let’s 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

Check The Demo

Enjoy!

Total 0 Votes
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top