Convert Text to Slugs

We may want to convert a plain string to a slugified version. Maybe we have a filter in Angular or Vue or some native JS feature, where we need to perform a slugify process.

Fortunately, with the use of regular expressions and JavaScript’s native replace() method, we can easily build and chain different patterns to replace non-accepted characters with URL friendly characters.

function slugify(text) {
    return text.toString().toLowerCase().trim()
        .replace(/é|è|ẽ|ẻ|ẹ|ê|ế|ề|ễ|ể|ệ/gi, 'e')
        .replace(/á|à|ã|ả|ạ|ă|ắ|ằ|ẵ|ẳ|ặ|â|ấ|ầ|ẫ|ẩ|ậ/gi, 'a')
        .replace(/ö|ő|ó|ò|õ|ỏ|ọ|ô|ố|ồ|ỗ|ổ|ộ|ơ|ớ|ờ|ỡ|ở|ợ/gi, 'o')
        .replace(/ü|ű|ú|ù|ũ|ủ|ụ|ư|ứ|ừ|ữ|ử|ự/gi, 'u')
        .replace(/í/gi, 'i')
        .replace(/đ/gi, 'd')
        .replace(/ļ/gi, 'l')
        .replace(/\s*$/g, '')
        .replace(/\s+/g, '-')
        .replace(/[^\w\-]+/g, '')
        .replace(/\-\-+/g, '-')
        .replace(/^-+/, '')
        .replace(/-+$/, '');
}
Of course, depending on your input language, you may extend the characters that need to be replaced.
Need a web developer? Maybe we can help, get in touch!