Ruffy
Ruffy

Reputation: 865

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.

Upvotes: 9

Views: 5400

Answers (2)

ninjagecko
ninjagecko

Reputation: 91094

Use the global regex capturing -. to replace each occurence, like this:

'margin-top-something'.replace(/(-.)/g, x=> x[1].toUpperCase())

Upvotes: 10

balpha
balpha

Reputation: 50898

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).

Upvotes: 21

Related Questions