How to generate slugs from titles in Node.js

June 18, 2020 Linda Walker Loading... Post a comment

A slug is the part of a URL that describes something about a webpage’s content. For example, we have a URL like this:

https://www.kindacode.com/article/how-to-generate-slugs-from-titles-in-node-js

Then the slug is:

how-to-generate-slugs-from-titles-in-node-js

A slug often contains only some “friendly” characters in lower case: a-z, 0-9, and the dash symbol. This is not a strict rule but is widely used by most English and Latin-based-language news websites: CNN, The New York Times, The Guardian…

Note: Most Chinese and Japanese websites don’t use slugs in their URLs.

How to generate slugs from titles in Node.js?

A slug of a page is ordinarily generated from this page’s title. And, here is how to get this matter done by using Node.js.

Note that the code snippet below only works well for English titles. If you’re using other languages like Spanish, French, Portuguese… then you will have to add some extra rules.

const titleToSlug = title => {
    let slug;

    // convert to lower case
    slug = title.toLowerCase();

    // remove special characters
    slug = slug.replace(/\`|\~|\!|\@|\#|\||\$|\%|\^|\&|\*|\(|\)|\+|\=|\,|\.|\/|\?|\>|\<|\'|\"|\:|\;|_/gi, '');
    // The /gi modifier is used to do a case insensitive search of all occurrences of a regular expression in a string

    // replace spaces with dash symbols
    slug = slug.replace(/ /gi, "-");
    
    // remove consecutive dash symbols 
    slug = slug.replace(/\-\-\-\-\-/gi, '-');
    slug = slug.replace(/\-\-\-\-/gi, '-');
    slug = slug.replace(/\-\-\-/gi, '-');
    slug = slug.replace(/\-\-/gi, '-');

    // remove the unwanted dash symbols at the beginning and the end of the slug
    slug = '@' + slug + '@';
    slug = slug.replace(/\@\-|\-\@|\@/gi, '');
    return slug;
};

// Testing
const title = "This is a special title, isn't it?";
const slug = titleToSlug(title);
console.log(slug);

Output:

this-is-a-special-title-isnt-it
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles

0
Would love your thoughts, please comment.x
()
x