DEV Community

miku86
miku86

Posted on

Diary - 2018.09.05

Regex is really great for finding and/or replacing things.

I have files named my-file-name.js or my_file_name.js
and want to change them to camelCase myFileName.js.

function toCamelCase(name) { // search for "-" or "_" followed by a character and replace it uppercased return name.replace(/[-_]([a-z])/gi, (_, char) => char.toUpperCase()); } 
Enter fullscreen mode Exit fullscreen mode

Explanation:

/ => starts the regex [-_] => - or _ ([a-z]) => all lowercase letters, captured in a group / => ends the regex gi => search all occurencies, ignore case (_, char) => char.toUpperCase() => _ is the passed in complete match, don't need it; return the capture group (= the letter after - or _) uppercased 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)