60

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.

vhs
  • 7,906
  • 2
  • 61
  • 66
Badrul
  • 551
  • 1
  • 5
  • 16
  • 1
    what have you tried? I'd use a regex to split by an uppercase letter to start with. – Jeff Jan 18 '19 at 01:12
  • 2
    Possible duplicate of [Javascript convert PascalCase to underscore\_case](https://stackoverflow.com/questions/30521224/javascript-convert-pascalcase-to-underscore-case) – Chris Turner Jan 18 '19 at 01:13
  • 3
    Java is to Javascript as Pain is to Painting, or Ham is to Hamster. They are completely different. It is highly recommended that aspiring coders try to learn the name of the language they're attempting to write code in. When you post a question, please tag it appropriately. – CertainPerformance Jan 18 '19 at 01:13

3 Answers3

151
const camelToSnakeCase = str => str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
Cody Gray
  • 230,875
  • 49
  • 477
  • 553
None
  • 1
  • 30
  • 155
  • 213
  • 4
    Its not work when i used Upper camel case to snake case. `ItemName`=`_item_name` – Badrul Jan 24 '19 at 08:33
  • 1
    @Badrul - yeah, it would. Try to fix it, post if you get stuck – None Jan 24 '19 at 15:12
  • 17
    @Badrul however that is more PascalCase – Luke May 14 '19 at 13:26
  • 7
    ItemName => item_name: ```const camel_to_snake = str => str[0].toLowerCase() + str.slice(1, str.length).replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);``` – e382df99a7950919789725ceeec126 Mar 30 '20 at 15:05
  • 6
    This version is working for upper camel case as well ```str.replace(/[A-Z]/g, (letter, index) => { return index == 0 ? letter.toLowerCase() : '_'+ letter.toLowerCase();});``` – Hrishi Jun 02 '21 at 10:03
  • 2
    my variant works fine with first uppercased letter: ```text.split(/(?=[A-Z])/).join('_').toLowerCase()``` – Evseev Vadim Nov 05 '21 at 14:55
  • @EvseevVadim -- that's not camel case then ;) Also, the question explicitly requests that that not be valid – None Nov 05 '21 at 15:01
  • @EvseevVadim, you are alright on my book... it is a very good solution, using the positive lookahead... good job! And thanks – marcelo-ferraz May 19 '22 at 21:25
18

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'));
Elliot
  • 770
  • 9
  • 17
  • Slightly modified version of the code: var result = (value .replace(/[^A-Za-z0-9_]/g, '_') .replace(/([A-Z]+)/g, " $1") .replace(/\s+/g, ' ') .trim() .toLowerCase() .replace(/\s/g, '_')); if (/^\d/.test(result)) { result = "x" + result; } – abasar Sep 13 '20 at 08:20
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
Amats
  • 498
  • 2
  • 7
  • 1
    you're going to need to re-join the array – None Jan 18 '19 at 01:17
  • @MarkKahn Forgot about that - Thanks! – Amats Jan 18 '19 at 02:10
  • Thanks! This is super helpful. for me, i also added a check to ensure that the new string wont start with an underscore by replacing your `'_'` with `(index != 0 ? '_': '')` and adding index as a parameter to the map function `...map((character, index) => {...` – MoralCode Aug 02 '20 at 22:42
  • I also used the answer at https://stackoverflow.com/a/55521416/ to add an check for alphabet characters to this function so that numbers and symbols (which are the same character after making them uppercase) don't cause this function to just keep doubling the mnumber of underscores when a snake_case string is passed in. However, this also has the flaw of limiting the input to only the hardcoded character set – MoralCode Aug 02 '20 at 23:07