- Instant help with your JavaScript coding problems

Convert camel case to snake case in JavaScript

Question:
How to convert camel case to snake case in JavaScript?
Answer:
function camelToSnake(str) {
    return str.replace(/[A-Z]/g, (c) => {return '_' + c.toLowerCase()});
}

console.log(camelToSnake('thisIsMyText')); // this_is_my_text
Description:

To convert an existing camel case string like thisIsMyText to a snake case version: this_is_my_text can be done using the built-in string replace function. The replace function accepts various parameters. In this case, we use the version where the first parameter is a regular expression and the second one is a replacer function:

replace(regexp, replacerFunction);

In this case, the matches are replaced with the value returned by the replacer function. So when we convert a camel case string first we need to find all uppercase letters and convert them to lowercase. Besides this, as snake case uses _ to separate words we also need to prefix the formatted letter with an underscore character.

str.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);

The above code in a more readable format is:

str.replace(/[A-Z]/g, (c) => { return '_' + c.toLowerCase() });

And, that's how you can convert camel case to snake case with a single line of code.

Share "How to convert camel case to snake case in JavaScript?"