Convert hyphens to camel case (camelCase)

Oscar Godson picture Oscar Godson · Jul 12, 2011 · Viewed 66.9k times · Source

With regex (i assume) or some other method, how can i convert things like:

marker-image or my-example-setting to markerImage or myExampleSetting.

I was thinking about just splitting by - then convert the index of that hypen +1 to uppercase. But it seems pretty dirty and was hoping for some help with regex that could make the code cleaner.

No jQuery...

Answer

user193476 picture user193476 · Jul 12, 2011

Try this:

var camelCased = myString.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });

The regular expression will match the -i in marker-image and capture only the i. This is then uppercased in the callback function and replaced.