Welcome, guest | Sign In | My Account | Store | Cart

"Slugify" a string so it has only alphanumeric and hyphen characters. Useful for URLs and filenames. This is a JavaScript (node.js too) version of Recipe 577257.

Note: It is missing the guarantee that only ascii characters are passed through. I don't know an NFKD equivalent in JavaScript-land.

JavaScript, 7 lines
1
2
3
4
5
6
7
_slugify_strip_re = /[^\w\s-]/g;
_slugify_hyphenate_re = /[-\s]+/g;
function slugify(s) {
  s = s.replace(_slugify_strip_re, '').trim().toLowerCase();
  s = s.replace(_slugify_hyphenate_re, '-');
  return s;
}
Created by Trent Mick on Tue, 12 Jul 2011 (MIT)
JavaScript recipes (69)
Trent Mick's recipes (28)

Required Modules

  • (none specified)

Other Information and Tasks