How to convert camelcase to snake case in Javascript?

JavascriptJson

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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 - Javascript

Try this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBadrulView Question on Stackoverflow
Solution 1 - JavascriptNoneView Answer on Stackoverflow
Solution 2 - JavascriptElliotView Answer on Stackoverflow
Solution 3 - JavascriptAmatsView Answer on Stackoverflow