Javascript convert PascalCase to underscore_case/snake_case

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(/^_/, ""));

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)