JS camelCase

JavaScript performance comparison

Test case created by Michael Yin

Info

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

Preparation code

<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

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
toCamelCase
string.toCamelCase();
pending…
camelizeOne
string.camelizeOne();
pending…
camelizeTwo
string.camelizeTwo();
pending…
otherCase toCamelCase
otherCase.toCamelCase();
pending…
otherCase camelizeOne
otherCase.camelizeOne();
pending…
otherCase camelizeTwo
otherCase.camelizeTwo();
pending…
noregex
string.toUpperCaseEachWord().toLowerCaseFirstChar();
pending…
otherCase noregex
otherCase.toUpperCaseEachWord().toLowerCaseFirstChar();
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment