-1

Can I apply a transformation to a captured group and perform a replacement in ES5?

I would like to transform dashed names (e.g. 'foo-bar) to camelcase (e.g. 'fooBar').

function camelify(str) {
  return (str.replace(/(\-([^-]{1}))/g, '$2'.toUpperCase()));
}
Ben Aston
  • 53,718
  • 65
  • 205
  • 331

1 Answers1

1

'$2'.toUpperCase(), the second argument you pass in, is equivalent to '$2' which does nothing but remove the dash.

You are looking for the callback parameter option in replace:

function camelify(str) {
  return str.replace(/-([^-])/g, function(match, $1) {
    return $1.toUpperCase();
  });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375