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".