JavaScript RegExp for CamelCase - CSS Hyphen Property

I am trying to change CSS properties like this.

-moz-border-radius 

In the CSS CSS property, for example:

 MozBorderRadius 

I am using this RegExp.

 var exp = new RegExp('-([az])', 'gi'); console.log('-moz-border-radius'.replace(exp, '$1')); 

All I have to do is convert $ 1 to uppercase so that it can work in cammelcaseify (yes, I made that word ...) my JavaScript based CSS property. Is it possible?

Thank.

+10
javascript regex replace
Feb 11 '11 at 13:35
source share
5 answers

You would be better off using the function as the second parameter in replace() , and you could also use the regular expression literal instead of the RegExp constructor:

 var replaced = '-moz-border-radius'.replace(/-([az])/gi, function(s, group1) { return group1.toUpperCase(); }); 
+24
Feb 11 2018-11-11T00:
source share

You need to pass a callback function instead of a string.

For example:

 var exp = /-([az])/gi; console.log('-moz-border-radius'.replace(exp, function(match, char, index, str) { return char.toUpperCase(); } )); 
+4
Feb 11 2018-11-11T00:
source share

Another, slightly more flexible answer:

 if (typeof String.prototype.toCamel !== 'function') { String.prototype.toCamel = function(){ return this.replace(/[-_]([az])/g, function (g) { return g[1].toUpperCase(); }) }; } 

Used as follows:

 '-moz-border-radius'.toCamel(); // "MozBorderRadius" 'moz-border-radius'.toCamel(); // "mozBorderRadius" 'moz_border_radius'.toCamel(); // "mozBorderRadius" '_moz_border_radius'.toCamel(); // "MozBorderRadius" 
+2
Mar 05 '14 at 15:11
source share

Additional Information...

MozBorderRadius = PascalCase AKA UpperCamelCase.

mozBorderRadius = camelCase.

moz_border_radius = snake_case.

 var string = "hyphen-delimited-to-camel-case" or var string = "snake_case_to_camel_case" function toCamelCase( string ){ return string.toLowerCase().replace(/(_|-)([az])/g, toUpperCase ); } function toUpperCase( string ){ return string[1].toUpperCase(); } Output: hyphenDelimitedToCamelCase 
0
Jun 17 '15 at 17:39
source share

You can also use indexOf with recursion for this task.

 input some-foo_sd_dsd-weqe output someFooSdDsdWeqe 

but runs slower

 MozBorderRadius test1: 3.535ms 

the code:

 function camelCased (str) { function check(symb){ let idxOf = str.indexOf(symb); if (idxOf === -1) { return str; } let letter = str[idxOf+1].toUpperCase(); str = str.replace(str.substring(idxOf+1,idxOf+2), ''); str = str.split(symb).join(idxOf !== -1 ? letter : ''); return camelCased(str); } return check('_') && check('-'); } console.log(camelCased ('-moz-border-radius')); 
0
Jan 11 '17 at 10:38 on
source share



All Articles