Javascript convert PascalCase to underscore_case

2019-02-05 16:57发布

问题:

How can I convert PascalCase string into underscore_case string? I need conversion of dots to underscore as well.

eg. convert

TypeOfData.AlphaBeta

into

type_of_data_alpha_beta

回答1:

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



回答2:

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

u're welcome

var s1 = 'someTextHere';
var s2 = 'SomeTextHere';

var o1 = s1.split(/(?=[A-Z])/).join('_').toLowerCase();
var o2 = s2.split(/(?=[A-Z])/).join('_').toLowerCase();

console.log(o1);
console.log(o2);



回答3:

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.



回答4:

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.



回答5:

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.