d
Amit DhamuSoftware Engineer
 

String to camelCase

1 minute read 00000 views

Function

const toCamelCase = str =>
  str
    .trim()
    .toLowerCase()
    .replace(/[-_\s.]+(.)?/g, (_, char) => (char ? char.toUpperCase() : ''))

Test Cases

describe('toCamelCase', () => {
  it.each([
    ['this is great', 'thisIsGreat'],
    ['This is great.', 'thisIsGreat'],
    [' this is great ', 'thisIsGreat'],
    ['this_is_great', 'thisIsGreat'],
    [' this-is great ', 'thisIsGreat'],
    ['THIS.-IS_GREAT', 'thisIsGreat'],
  ])('converts %p to %p', (input, output) => {
    expect(toCamelCase(input)).toEqual(output)
  })
})