JSFiddle - React, Tailwind, and code Playground

by Travis Harris

JavaScript

//For those who'd rather not mess with natives
toCamelCase = function(string){
    string = string.replace(/[_\-A-Z]([^_\-A-Z])/g, function($0,$1){return $0.charAt(0).match(/[A-Z]/)?$0:$1.toUpperCase();});
    return string.charAt(0).toLowerCase() + string.substring(1);
}
toUpperCamelCase = function(string){
    string = toCamelCase(string);
    return string.charAt(0).toUpperCase() + string.substring(1);
}

//Or for those comfortable extending natives
if (!String.prototype.toCamelCase)String.prototype.toCamelCase = function(){
    string = this.replace(/[_\-A-Z]([^_\-A-Z])/g, function($0,$1){return $0.charAt(0).match(/[A-Z]/)?$0:$1.toUpperCase();});
    return string.charAt(0).toLowerCase() + string.substring(1);
}
if (!String.prototype.toUpperCamelCase)String.prototype.toUpperCamelCase = function(){
    string = toCamelCase(this);
    return string.charAt(0).toUpperCase() + string.substring(1);
}

var tests = [
    'something-like-this1',
    'something_like_this2',
    'somethingLikeThis3',
    'SomethingLikeThis4'
];
tests.forEach(function(test){
    console.log('testing:',test);
    console.log(' toCamelCase:',toCamelCase(test));
    console.log(' toUpperCamelCase:',toUpperCamelCase(test));
    console.log(' String.toCamelCase:',test.toCamelCase());
    console.log(' String.toUpperCamelCase:',test.toUpperCamelCase());
});