'How to convert camelcase to snake case in Javascript? [closed]

I want to convert a string of that is in camel case to snake case using TypeScript.

Remember that the "snake case" refers to the format style in which each space is replaced by an underscore (_) character and the first letter of each word written in lowercase.

Example: fieldName to field_name should be a valid conversion, but FieldName to Field_Name is not valid.



Solution 1:[1]

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

Solution 2:[2]

You could do something like this:

function camelToUnderscore(key) {
   var result = key.replace( /([A-Z])/g, " $1" );
   return result.split(' ').join('_').toLowerCase();
}

console.log(camelToUnderscore('itemName'));

Solution 3:[3]

Try this:

function toSnakeCase(inputString) {
    return inputString.split('').map((character) => {
        if (character == character.toUpperCase()) {
            return '_' + character.toLowerCase();
        } else {
            return character;
        }
    })
    .join('');
}
// x = item_name

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cody Gray
Solution 2 Elliot
Solution 3