Search code examples
javascriptregexcamelcasing

Convert hyphens to camel case (camelCase)


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


Solution

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