-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
  • 49,455
  • 61
  • 188
  • 322

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
  • 572,313
  • 128
  • 898
  • 1,281