Javascript 将 PascalCase 转换为 underscore_case

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30521224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:19:36  来源:igfitidea点击:

Javascript convert PascalCase to underscore_case

javascriptstringcase-conversion

提问by zahmati

How can I convert PascalCasestring into underscore_casestring? I need conversion of dots to underscore as well.

如何将PascalCase字符串转换为underscore_case字符串?我也需要将点转换为下划线。

eg. convert

例如。转变

TypeOfData.AlphaBeta

into

进入

type_of_data_alpha_beta

回答by Avinash Raj

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(/^_/, ""));
    
  • 捕获所有大写字母并匹配前面的可选点字符。

  • 然后将捕获的大写字母转换为小写字母,然后返回以使用_as 前导字符替换函数。这将通过在替换部分中使用匿名函数来实现。

  • 这会将起始大写字母替换为_+lowercase_letter。

  • 最后删除起始下划线将为您提供所需的输出。

    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. MotorRPMinto motor_rpminstead of motor_r_p_m? or BatteryAAAinto battery_aaainstead of battery_a_a_a?

当整个单词为大写时,任何阻止它的方法。例如。MotorRPM进入motor_rpm而不是motor_r_p_m?或BatteryAAA进入battery_aaa而不是battery_a_a_a

var s = 'MotorRMP';
alert(s.replace(/\.?([A-Z]+)/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));

回答by coHyman

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);

回答by Wtower

Alternatively using lodash:

或者使用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, kebabCaseetc.

Lodash是一个很好的图书馆给快捷方式到许多日常JS tasks.There是许多其他类似的字符串处理函数,例如camelCasekebabCase等等。

回答by Hgehlhausen

"alphaBetaGama".replace(/([A-Z])/g, "_").toLowerCase() // alpha_beta_gamma

Problem- Need to convert a camel-case string ( such as a property name ) into underscore style to meet interface requirements or for meta-programming.

问题- 需要将驼峰式字符串(例如属性名称)转换为下划线样式以满足接口要求或元编程。

ExplanationThis line uses a feature of regular expressions where it can return a matched result ( first pair of () is $1, second is $2, etc ).

说明这一行使用了正则表达式的一个特性,它可以返回匹配的结果(第一对 () is $1,第二对 is $2,等等)。

Each match in the string is converted to have an underscore ahead of it with _$1string provided. At that point the string looks like alpha_Beta_Gamma.

字符串中的每个匹配项都被转换为在其前面带有下划线并提供_$1字符串。在这一点上,字符串看起来像alpha_Beta_Gamma.

To correct the capitalization, the entire string is converted toLowerCase().

为了更正大小写,整个字符串被转换为LowerCase()。

Since toLowerCase is a fairly expensive operation, its best not to put it in the looping handler for each match-case, and run it once on the entire string.

由于 toLowerCase 是一个相当昂贵的操作,最好不要将它放在每个匹配案例的循环处理程序中,而是在整个字符串上运行一次。

After toLowerCaseit the resulting string is alpha_beta_gamma( in this example )

toLowerCase它之后产生的字符串是alpha_beta_gamma(在这个例子中)

回答by Scott P.

This solution solves the non-trailing acronym issue with the solutions above

此解决方案解决了上述解决方案的非尾随首字母缩略词问题

I ported the code in 1175208from Python to JavaScript.

我将1175208 中的代码从 Python移植到 JavaScript。

Javascript Code

Javascript代码

function camelToSnakeCase(text) {
    return text.replace(/(.)([A-Z][a-z]+)/, '_').replace(/([a-z0-9])([A-Z])/, '_').toLowerCase()
}

Working Examples:

工作示例:

camelToSnakeCase('thisISDifficult') -> this_is_difficult

camelToSnakeCase('thisISNT') -> this_isnt

camelToSnakeCase('somethingEasyLikeThis') -> something_easy_like_this

回答by errata

This will get you pretty far: https://github.com/domchristie/humps

这会让你走得很远:https: //github.com/domchristie/humps

You will probably have to use regex replace to replace the "." with an underscore.

您可能必须使用正则表达式替换来替换“。” 带下划线。

回答by Gabit Kemelov

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.

试试这个功能,希望对你有帮助。

回答by user3413723

"TestString".replace(/[A-Z]/g, val => "_" + val.toLowerCase()).replace(/^_/,"")

replaces all uppercase with an underscore and lowercase, then removes the leading underscore.

用下划线和小写字母替换所有大写字母,然后删除前导下划线。

回答by Ahmed Khaled

I found thisbut I edited it so suit your question.

我找到了这个,但我对其进行了编辑以适合您的问题。

const camelToSnakeCase = str => str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`).replace(/^_/,'')