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
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.
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.
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
intomotor_rpm
instead ofmotor_r_p_m
? orBatteryAAA
intobattery_aaa
instead ofbattery_a_a_a
?
var s = 'MotorRMP'; alert(s.replace(/\.?([A-Z]+)/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With