Generating slugs (v5)

Revision 5 of this benchmark created by Kristof Neirynck on


Description

To generate a slug, do this:

  • Convert the string to lowercase
  • Replace every non-alphanumeric character with a hyphen (-)
  • Merge consecutive hyphens into one

Note that following these steps still won’t turn "ïñtërnâtiônàlizætiøn" into "internationalization". This was not a requirement in this case.

Preparation HTML

<script>
  var arr = [
   'This is just a test',
   'Some “weird” characters: ©™® Awesome',
   'Lorem ipsum 123 dolor'
   ];
  
  // → "this-is-just-a-test"
  // → "some-weird-characters-awesome"
  // → "lorem-ipsum-123-dolor"
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Using several .replace()s
var i = arr.length;
while (i--) {
 arr[i].toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/[-]+/g, '-').replace(/^-|-$/g, '');
};
ready
Using .match() and .join()
var i = arr.length;
while (i--) {
 arr[i].toLowerCase().match(/[a-z0-9]+/ig).join('-');
};
ready
Using several .replace()s (but trying to reduce the number of regexes)
var i = arr.length;
var a = /[^a-z0-9-]*-+[^a-z0-9-]*|-*[^a-z0-9-]+-*/g;
var ar = '-';
var b = /^-|-$/g;
var br = '';
while (i--) {
 arr[i].toLowerCase().replace(a, ar).replace(b, br);
};
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Mathias Bynens on
  • Revision 5: published by Kristof Neirynck on
  • Revision 7: published by mathiasbaert on
  • Revision 8: published by imma on
  • Revision 9: published by Tri on
  • Revision 10: published by Ross on