问题描述
如何将PascalCase
字符串转换为underscore_case/snake_case
字符串?我还需要将点转换为下划线.
How can I convert PascalCase
string into underscore_case/snake_case
string? I need to convert dots into underscores as well.
例如.转换
TypeOfData.AlphaBeta
进入
type_of_data_alpha_beta
推荐答案
您可以尝试以下步骤.
捕获所有大写字母并匹配前面的可选点字符.
Capture all the uppercase letters and also match the preceding optional dot character.
然后将捕获的大写字母转换为小写字母,然后返回以_
作为前导字符的replace函数.这将通过在替换部分中使用匿名函数来实现.
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.
这会将起始大写字母替换为 _
+ lowercase_letter.
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(/^_/, ""));
或
var s = 'TypeOfData.AlphaBeta';
alert(s.replace(/\.?([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
当整个单词都是大写时,任何阻止它的方法.例如.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(/^_/, ""));
这篇关于Javascript 将 PascalCase 转换为 underscore_case/snake_case的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!