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()); } 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
Top comments (0)