danielwertheim

danielwertheim


notes from a passionate developer

Share


Sections


Tags


Disclaimer

This is a personal blog. The opinions expressed here represent my own and not those of my employer, nor current or previous. All content is published "as is", without warranty of any kind and I don't take any responsibility and can't be liable for any claims, damages or other liabilities that might be caused by the content.

Simple JavaScript slugify

I confess. Me and regular expressions aren’t buddy, buddies. So it took some trial and error before reaching this point with something useful in the context of generating slugs. There are probably tons of scripts like these, but here we go.

if (!String.prototype.toSlug) {
  String.prototype.toSlug = function () {
    return this.toLowerCase()
      .replace(/s/g, '-')
      .replace(/&/g, 'and')
      .replace(/[^w-]+/g,'')
      .replace(/[-*]+/g,'-')          
      .trim();
  };
}

With this we can now get something that looks like slugs.

console.log("Some  text".toSlug());
=> some-text

console.log("'Some'!#%"text"".toSlug());
=> sometext

console.log("Some----text & some 123".toSlug());
=> some-text-and-some-123

Covers my needs. Feel free to drop comments about good improvements.

Cheers,

//Daniel

View Comments