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
);
Written by Ezequias Dinella
Related protips
5 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Js
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#