JS camelCase

Benchmark created by Michael Yin on


Description

Test the speed of various methods to camel case a string. http://stackoverflow.com/questions/2970525/javascript-regex-camel-case-sentence-case

Preparation HTML

<script>
  String.prototype.toCamelCase = function() {
      return this
          .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
          .replace(/\s/g, '')
          .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
  };
  
  String.prototype.camelizeOne = function() {
    return this.replace(/(?:^\w|[A-Z]|\b\w)/g, function(letter, index) {
      return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
    }).replace(/\s+/g, '');
  };
  
  String.prototype.camelizeTwo = function() {
    return this.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
      if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
      return index == 0 ? match.toLowerCase() : match.toUpperCase();
    });
  };
  
  String.prototype.toUpperCaseFirstChar = function() {
      return this.substr( 0, 1 ).toUpperCase() + this.substr( 1 );
  };
  
  String.prototype.toLowerCaseFirstChar = function() {
      return this.substr( 0, 1 ).toLowerCase() + this.substr( 1 );
  };
  
  String.prototype.toUpperCaseEachWord = function( delim ) {
      delim = delim ? delim : ' ';
      return this.split( delim ).map( function(v) { return v.toUpperCaseFirstChar() } ).join( delim );
  };
  
  String.prototype.toLowerCaseEachWord = function( delim ) {
      delim = delim ? delim : ' ';
      return this.split( delim ).map( function(v) { return v.toLowerCaseFirstChar() } ).join( delim );
  };
  
  var string = "How can I convert a string into camel case using javascript regex?";
  
  var otherCase = "BeepBoopBeep";
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
toCamelCase
string.toCamelCase();
ready
camelizeOne
string.camelizeOne();
ready
camelizeTwo
string.camelizeTwo();
ready
otherCase toCamelCase
otherCase.toCamelCase();
ready
otherCase camelizeOne
otherCase.camelizeOne();
ready
otherCase camelizeTwo
otherCase.camelizeTwo();
ready
noregex
string.toUpperCaseEachWord().toLowerCaseFirstChar();
ready
otherCase noregex
otherCase.toUpperCaseEachWord().toLowerCaseFirstChar();
ready

Revisions

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

  • Revision 1: published by Michael Yin on