Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalizing the letter following a dash and removing the dash

If you haven't guessed from the title, I'm trying to convert CSS property syntax to JS syntax using JS. That means I want to take the input 'margin-top' and convert it to 'marginTop'. I know that this could be done easily with a few lines and the replace function, but I was wondering if regex would have a simpler, more compact solution.

So, my question is what regular expression would I use to replace -\w with no dash and the first letter of the word uppercased. If this happens to be impossible, what would be the most minimalistic solution with the replace function?

Thanks for any help.

like image 314
Ruffy Avatar asked May 15 '11 15:05

Ruffy


2 Answers

If you search the jQuery source for camelCase, you'll find this function:

function camelCase (string) {
    return string.replace( /-([a-z])/ig, function( all, letter ) {
        return letter.toUpperCase();
    });
}

(except that in there, the regex and the call back are defined separately).

like image 71
balpha Avatar answered Nov 16 '22 00:11

balpha


'margin-top-something'.replace(/(-.)/g,function(x){return x[1].toUpperCase()})
like image 26
ninjagecko Avatar answered Nov 16 '22 00:11

ninjagecko