Generating slugs (v10)

Revision 10 of this benchmark created by Ross 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>
  // custom colors
  ui.browserscope.colors = ['pink', '#43C6DB'];

  var arr = [
   'This is just a test', // → "this-is-just-a-test"
   'Some “weird” characters: ©™® Awesome', // → "some-weird-characters-awesome"
   'Lorem ipsum 123 dolor' // → "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

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