Last Updated: September 09, 2019
·
51.11K
· edinella

Convert snake-case to camelCase

function snakeToCamel(s){
    return s.replace(/(\-\w)/g, function(m){return m[1].toUpperCase();});
}

or as more readable code

var snakeCaseString = 'lorem-ipsum';

var find = /(\-\w)/g;
var convert =  function(matches){
    return matches[1].toUpperCase();
};
var camelCaseString = snakeCaseString.replace(
    find,
    convert
);

5 Responses
Add your response

Btw, snake case looks_like_this, your example is for converting hyphen separated words into camel case.

To do snake case, the regex in your example should look like this:

/(_\w)/g
over 1 year ago ·

Why do you need the () capturing group? It works without that too:

value.replace(/_\w/g, function(m) {
  return m[1].toUpperCase();
});
over 1 year ago ·

@lethys is totally right. That is a kebab-case regex.

over 1 year ago ·

Shorter:

value.replace(/_\w/g, (m) => m[1].toUpperCase() );
over 1 year ago ·

Actually you do need the capturing group, because you want to omit the underscore in the result:

value.replace(/_(\w)/g, (m => m[1].toUpperCase()));
over 1 year ago ·