JavaScript RegExp to CamelCase a hyphened CSS property
Another, slightly more flexible answer:
if (typeof String.prototype.toCamel !== 'function') {
String.prototype.toCamel = function(){
return this.replace(/[-_]([a-z])/g, function (g) { return g[1].toUpperCase(); })
};
}
Used like this:
'-moz-border-radius'.toCamel(); // "MozBorderRadius"
'moz-border-radius'.toCamel(); // "mozBorderRadius"
'moz_border_radius'.toCamel(); // "mozBorderRadius"
'_moz_border_radius'.toCamel(); // "MozBorderRadius"
You would be better off using a function as the second parameter in replace()
, and you could also use a regex literal instead of the RegExp
constructor:
var replaced = '-moz-border-radius'.replace(/-([a-z])/gi, function(s, group1) {
return group1.toUpperCase();
});
You need to pass a callback function instead of a string.
For example:
var exp = /-([a-z])/gi;
console.log('-moz-border-radius'.replace(exp,
function(match, char, index, str) {
return char.toUpperCase();
}
));