91

How can I convert PascalCase string into underscore_case/snake_case string? I need to convert dots into underscores as well.

eg. convert

TypeOfData.AlphaBeta 

into

type_of_data_alpha_beta 
1

11 Answers 11

115
str.split(/\.?(?=[A-Z])/).join('_').toLowerCase(); 

u're welcome

var s1 = 'someTextHere'; var s2 = 'SomeTextHere'; var s3 = 'TypeOfData.AlphaBeta'; var o1 = s1.split(/\.?(?=[A-Z])/).join('_').toLowerCase(); var o2 = s2.split(/\.?(?=[A-Z])/).join('_').toLowerCase(); var o3 = s3.split(/\.?(?=[A-Z])/).join('_').toLowerCase(); console.log(o1); console.log(o2); console.log(o3);

Sign up to request clarification or add additional context in comments.

1 Comment

It does not work with ' SomeTextHere' because of the leading whitespace. Adding a trim before the split solves it.
110

You could try the below steps.

  • Capture all the uppercase letters and also match the preceding optional dot character.

  • Then convert the captured uppercase letters to lowercase and then return back to replace function with an _ as preceding character. This will be achieved by using anonymous function in the replacement part.

  • This would replace the starting uppercase letter to _ + lowercase_letter.

  • Finally removing the starting underscore will give you the desired output.

    var s = 'TypeOfData.AlphaBeta'; console.log(s.replace(/(?:^|\.?)([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, "")); 

OR

var s = 'TypeOfData.AlphaBeta'; alert(s.replace(/\.?([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));

any way to stop it for when a whole word is in uppercase. eg. MotorRPM into motor_rpm instead of motor_r_p_m? or BatteryAAA into battery_aaa instead of battery_a_a_a?

var s = 'MotorRMP'; alert(s.replace(/\.?([A-Z]+)/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));

5 Comments

Thanks, any way to stop it for when a whole word is in uppercase. eg. MotorRMP into motor_rpm instead of motor_r_p_m? or BatteryAAA into battery_aaa instead of battery_a_a_a.
alert(s.replace(/\.?([A-Z]+)/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
The above solutions fail with "attributeGUILabel" which should convert to "attribute_gui_label".
I found a solution that works.. see my answer below
I would prefer without callback s.replace(/\.?([A-Z]+)/g, '_$1').toLowerCase().replace(/^_/, "")
65

Alternatively using lodash:

lodash.snakeCase(str); 

Example:

_.snakeCase('TypeOfData.AlphaBeta'); // ➜ 'type_of_data_alpha_beta' 

Lodash is a fine library to give shortcut to many everyday js tasks.There are many other similar string manipulation functions such as camelCase, kebabCase etc.

2 Comments

Wow thanks for this, I was using my own toSnakeCase, toTitleCase(_.startCase), toCamelCase. Thanks to this I now switched to lodash and it works much better then mine! I had no idea lodash had this!
Also thank you! I use lodash every day and didn't realize it could do this!
12

This solution solves the non-trailing acronym issue with the solutions above

I ported the code in 1175208 from Python to JavaScript.

Javascript Code

function camelToSnakeCase(text) { return text.replace(/(.)([A-Z][a-z]+)/, '$1_$2').replace(/([a-z0-9])([A-Z])/, '$1_$2').toLowerCase() } 

Working Examples:

camelToSnakeCase('thisISDifficult') -> this_is_difficult camelToSnakeCase('thisISNT') -> this_isnt camelToSnakeCase('somethingEasyLikeThis') -> something_easy_like_this 

Comments

11
"alphaBetaGama".replace(/([A-Z])/g, "_$1").toLowerCase() // alpha_beta_gamma 

Problem - Need to convert a camel-case string ( such as a property name ) into underscore style to meet interface requirements or for meta-programming.

Explanation This line uses a feature of regular expressions where it can return a matched result ( first pair of () is $1, second is $2, etc ).

Each match in the string is converted to have an underscore ahead of it with _$1 string provided. At that point the string looks like alpha_Beta_Gamma.

To correct the capitalization, the entire string is converted toLowerCase().

Since toLowerCase is a fairly expensive operation, its best not to put it in the looping handler for each match-case, and run it once on the entire string.

After toLowerCase it the resulting string is alpha_beta_gamma ( in this example )

Comments

1

This will get you pretty far: https://github.com/domchristie/humps

You will probably have to use regex replace to replace the "." with an underscore.

Comments

1

I found this but I edited it so suit your question.

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

Comments

1

Good examples for js:

  1. Snake Case
  2. Kebab Case
  3. Camel Case
  4. Pascal Case

have here

Comments

0
function toCamelCase(s) { // remove all characters that should not be in a variable name // as well underscores an numbers from the beginning of the string s = s.replace(/([^a-zA-Z0-9_\- ])|^[_0-9]+/g, "").trim().toLowerCase(); // uppercase letters preceeded by a hyphen or a space s = s.replace(/([ -]+)([a-zA-Z0-9])/g, function(a,b,c) { return c.toUpperCase(); }); // uppercase letters following numbers s = s.replace(/([0-9]+)([a-zA-Z])/g, function(a,b,c) { return b + c.toUpperCase(); }); return s; } 

Try this function, hope it helps.

1 Comment

Isn't it wrong in direction? CamelToUnderscore is needed.
0
"TestString".replace(/[A-Z]/g, val => "_" + val.toLowerCase()).replace(/^_/,"") 

replaces all uppercase with an underscore and lowercase, then removes the leading underscore.

Comments

0

A Non-Regex Answer that converts PascalCase to snake_case

Note: I understand there are tons of good answers which solve this question elegantly. I was recently working on something similar to this where I chose not to use regex. So I felt to answer a non-regex solution to this.

const toSnakeCase = (str) => { return str.slice(0,1).toLowerCase() + str.split('').slice(1).map((char) => { if (char == char.toUpperCase()) return '_' + char.toLowerCase(); else return char; }).join(''); } 

Eg.

inputString = "ILoveJavascript" passed onto toSnakeCase() 

would become "i_love_javascript"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.