Catalin Vasile

I'm a design-focused engineer.

JavaScript Bits: How to convert snake-case to camelCase?

Converting a String from snake case to camel case in JavaScript requires three simple steps:

  1. First, capture a group of - or _ and the next letter afterwards.
  2. Remove both - and _ from the captured group.
  3. Replace the remaining letter with its uppercase version.

Pretty straightforward, right? Let’s see how it looks in ES6:

const snakeToCamel = (str) => str.replace(
    /([-_][a-z])/ig,
    (group) => group.toUpperCase()
                    .replace('-', '')
                    .replace('_', '')
);

snakeToCamel('my-snake-string'); // mySnakeString

Loving these short articles? Make sure to subscribe!

Subscribe

Be the first to know when I publish a new article on the blog.

No spam. You can unsubscribe at any time.


Comments