Generating slugs (v9)

Revision 9 of this benchmark created by Tri 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 t='';
  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"
  ];





        function charloop(str) {
            str = str.toLocaleLowerCase();
var L=str.length;
var ar='';
var j;
var c;
var z = false;


for(j=0;j<L;j++){

c=str.charCodeAt(j);

if((c>=48&&c<=57)

                      ||
                    (  
                       c >= 97
                        &&c <= 122
                    )

   ){

    ar += str[j];
      z = false;
}
else if (z === false) {
  ar += '-';
    z = true;
    
  

}







}

return ar

        }







function severalreplace(str){
return str.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/[-]+/g, '-').replace(/^-|-$/g, '');
}


function matchjoin(str){
return  str.toLowerCase().match(/[a-z0-9]+/ig).join('-');
}
</script>

Setup

t='';

Teardown


    t='';
  

Test runner

Ready to run.

Testing in
TestOps/sec
several replace
var i = arr.length;
while (i--) {
t=severalreplace(arr[i])
}
ready
matchjoin
var i = arr.length;
while (i--) {
t=matchjoin(arr[i])
}
 
ready
char loop
var i = arr.length;
while (i--) {
t=charloop(arr[i])
}
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