JS camelCase
JavaScript performance comparison
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.
| Test | Ops/sec | |
|---|---|---|
toCamelCase |
|
pending… |
camelizeOne |
|
pending… |
camelizeTwo |
|
pending… |
otherCase toCamelCase |
|
pending… |
otherCase camelizeOne |
|
pending… |
otherCase camelizeTwo |
|
pending… |
noregex |
|
pending… |
otherCase noregex |
|
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:
- Revision 1: published by Michael Yin
- Revision 2: published by leavingme
0 comments