iprsng
Last Updated: November 18, 2017
·
32.25K
· 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
);

4 Responses
Add your response

12119

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 ·
25986

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 ·
28539

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

over 1 year ago ·
29435

Shorter:

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