Generating slugs (v8)

Revision 8 of this benchmark created by imma 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', // → "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 3 .replace()s - case sensitive
var i = arr.length;
while (i--) {
 arr[i].toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/[-]+/g, '-').replace(/^-|-$/g, '');
};
ready
Using .match() and .join() - case insensitive
var i = arr.length;
while (i--) {
 arr[i].toLowerCase().match(/[a-z0-9]+/ig).join('-');
};
ready
Using 2 .replace()s - case sensitive
var i = arr.length;
while (i--) {
 arr[i].toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
};
ready
Using .match() and .join() - case sensitive
var i = arr.length;
while (i--) {
 arr[i].toLowerCase().match(/[a-z0-9]+/g).join('-');
};
ready
Using 2 .replace()s - case insensitive
var i = arr.length;
while (i--) {
 arr[i].toLowerCase().replace(/[^a-z0-9]+/ig, '-').replace(/^-|-$/g, '');
};
ready
Using 3 .replace()s - case insensitive
var i = arr.length;
while (i--) {
 arr[i].toLowerCase().replace(/[^a-z0-9-]+/ig, '-').replace(/[-]+/g, '-').replace(/^-|-$/g, '');
};
ready
trim down before lcase
var i = arr.length;
while (i--) {
 arr[i].replace(/^\W+|\W+$/g,'').replace(/\W+/g,'-').toLowerCase(); }
ready
trim ends before inserting hyphens
var i = arr.length;
while (i--) {
 arr[i].toLowerCase().replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, '').replace(/[^a-z0-9]+/g, '-');}
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