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".
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
slug($('#field').val())
original by: http://dense13.com/blog/2009/05/03/converting-string-to-slug-javascript/
EDIT: extended for more language specific chars:
var from = "ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆĞÍÌÎÏİŇÑÓÖÒÔÕØŘŔŠŞŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇğíìîïıňñóöòôõøðřŕšşťúůüùûýÿžþÞĐđßÆa·/_,:;";
var to = "AAAAAACCCDEEEEEEEEGIIIIINNOOOOOORRSSTUUUUUYYZaaaaaacccdeeeeeeeegiiiiinnooooooorrsstuuuuuyyzbBDdBAa------";
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...
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>
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
Combining a variety of elements from the answers here with normalize provides good coverage. Keep the order of operations to incrementally clean the url.
function clean_url(s) {
return s.toString().normalize('NFD').replace(/[\u0300-\u036f]/g, "") //remove diacritics
.toLowerCase()
.replace(/\s+/g, '-') //spaces to dashes
.replace(/&/g, '-and-') //ampersand to and
.replace(/[^\w\-]+/g, '') //remove non-words
.replace(/\-\-+/g, '-') //collapse multiple dashes
.replace(/^-+/, '') //trim starting dash
.replace(/-+$/, ''); //trim ending dash
}
normlize('NFD')
breaks accented characters into their components, which are basic letters plus diacritics (the accent part). replace(/[\u0300-\u036f]/g, "")
purges all the diacritics, leaving the basic letters by themselves. The rest is explained with inline comments.
All you needed was a plus :)
$("#Restaurant_Name").keyup(function() {
var Text = $(this).val();
Text = Text.toLowerCase();
var regExp = /\s+/g;
Text = Text.replace(regExp,'-');
$("#Restaurant_Slug").val(Text);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With