Convert dash-separated string to camelCase?

Solution 1:

Yes (edited to support non-lowercase input and Unicode):

function camelCase(input) { 
    return input.toLowerCase().replace(/-(.)/g, function(match, group1) {
        return group1.toUpperCase();
    });
}

See more about "replace callbacks" on MDN's "Specifying a function as a parameter" documentation.

The first argument to the callback function is the full match, and subsequent arguments are the parenthesized groups in the regex (in this case, the character after the the hyphen).

Solution 2:

Another method using reduce:

function camelCase(str) {
  return str
    .split('-')
    .reduce((a, b) => a + b.charAt(0).toUpperCase() + b.slice(1));
}

Solution 3:

You can match on the word character after each dash (-) or the start of the string, or you could simplify by matching the word character after each word boundary (\b):

function camelCase(s) {
  return (s||'').toLowerCase().replace(/(\b|-)\w/g, function(m) {
    return m.toUpperCase().replace(/-/,'');
  });
}
camelCase('foo-bar'); // => 'FooBar'
camelCase('FOo-BaR-gAH'); // => 'FooBarGah'