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.
MotorRPMintomotor_rpminstead ofmotor_r_p_m? orBatteryAAAintobattery_aaainstead ofbattery_a_a_a?
var s="MotorRMP";
alert(s.replace(/\.?([A-Z]+)/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));