How to convert camelcase to snake case in Javascript?
JavascriptJsonJavascript 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