Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript convert PascalCase to underscore_case/snake_case

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 
like image 221
zahmati Avatar asked May 29 '15 04:05

zahmati


People also ask

Can I use snake case in JavaScript?

Snake case (also referred to as underscore case) is when all the letters of the word are lower case but delimited by an underscore. We seldom use the snake case coding convention in C-style languages like Java, JavaScript, and TypeScript.

What is camelCase in JavaScript?

Camel case is the practice of writing phrases such that each word or abbreviation in the middle of the phrase begins with a capital letter, with no intervening spaces or punctuation. For example, Concurrent hash maps in camel case would be written as − ConcurrentHashMaps.


1 Answers

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(/^_/, ""));
like image 184
Avinash Raj Avatar answered Oct 11 '22 12:10

Avinash Raj