javascript - How to convert a Title to a URL slug in jQuery?

ID : 20187

viewed : 26

Tags : javascriptjqueryregexslugslugifyjavascript

Top 5 Answer for javascript - How to convert a Title to a URL slug in jQuery?

vote vote


I have no idea where the 'slug' term came from, but here we go:

function convertToSlug(Text) {   return Text.toLowerCase()              .replace(/ /g, '-')              .replace(/[^\w-]+/g, ''); } 

The first replace method will change spaces to hyphens, second, replace removes anything not alphanumeric, underscore, or hyphen.

If you don't want things "like - this" turning into "like---this" then you can instead use this one:

function convertToSlug(Text) {   return Text.toLowerCase()              .replace(/[^\w ]+/g, '')              .replace(/ +/g, '-'); } 

That will remove hyphens (but no spaces) on the first replace, and in the second replace it will condense consecutive spaces into a single hyphen.

So "like - this" comes out as "like-this".

vote vote


var slug = function(str) {   str = str.replace(/^\s+|\s+$/g, ''); // trim   str = str.toLowerCase();    // remove accents, swap ñ for n, etc   var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;";   var to   = "aaaaaeeeeeiiiiooooouuuunc------";   for (var i = 0, l = from.length; i < l; i++) {     str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));   }    str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars            .replace(/\s+/g, '-') // collapse whitespace and replace by -            .replace(/-+/g, '-'); // collapse dashes    return str; }; 

and try


original by:

EDIT: extended for more language specific chars:

var from = "ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆĞÍÌÎÏİŇÑÓÖÒÔÕØŘŔŠŞŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇğíìîïıňñóöòôõøðřŕšşťúůüùûýÿžþÞĐđßÆa·/_,:;"; var to   = "AAAAAACCCDEEEEEEEEGIIIIINNOOOOOORRSSTUUUUUYYZaaaaaacccdeeeeeeeegiiiiinnooooooorrsstuuuuuyyzbBDdBAa------"; 
vote vote


First of all, regular expressions should not have surrounding quotes, so '/\s/g' should be /\s/g

In order to replace all non-alphanumerical characters with dashes, this should work (using your example code):

$("#Restaurant_Name").keyup(function() {   var Text = $(this).val();   Text = Text.toLowerCase();   Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');   $("#Restaurant_Slug").val(Text);         }); 

That should do the trick...

vote vote


Hope this can save someone's day...

/* Encode string to slug */ function convertToSlug( str ) {        //replace all special characters | symbols with a space   str = str.replace(/[`~!@#$%^&*()_\-+=\[\]{};:'"\\|\/,.<>?\s]/g, ' ')            .toLowerCase();        // trim spaces at start and end of string   str = str.replace(/^\s+|\s+$/gm,'');        // replace space with dash/hyphen   str = str.replace(/\s+/g, '-');      document.getElementById("slug-text").innerHTML = str;   //return str; }
<input    type="text"    onload="convertToSlug(this.value)"    onkeyup="convertToSlug(this.value)"   value="Try it Yourself"  /> <p id="slug-text"></p>

vote vote


I found a good and complete solution for English

function slugify(string) {   return string     .toString()     .trim()     .toLowerCase()     .replace(/\s+/g, "-")     .replace(/[^\w\-]+/g, "")     .replace(/\-\-+/g, "-")     .replace(/^-+/, "")     .replace(/-+$/, ""); } 

Some examples of it in use:

slugify(12345); // "12345"  slugify("  string with leading   and   trailing whitespace    "); // "string-with-leading-and-trailing-whitespace"  slugify("mIxEd CaSe TiTlE"); // "mixed-case-title"  slugify("string with - existing hyphens -- "); // "string-with-existing-hyphens"  slugify("string with Special™ characters"); // "string-with-special-characters" 

Thanks to Andrew Stewart

Top 3 video Explaining javascript - How to convert a Title to a URL slug in jQuery?