问题描述
如何将PascalCase
字符串转换为underscore_case
字符串?我还需要将点转换为下划线.
How can I convert PascalCase
string into underscore_case
string? I need conversion of dots to underscore as well.
例如转换
TypeOfData.AlphaBeta
进入
type_of_data_alpha_beta
推荐答案
您可以尝试以下步骤.
-
捕获所有大写字母并匹配前面的可选点字符.
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.
这会将起始大写字母替换为_
+ 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(/^_/, ""));
OR
var s = 'TypeOfData.AlphaBeta';
alert(s.replace(/\.?([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
var s = 'MotorRMP';
alert(s.replace(/\.?([A-Z]+)/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
这篇关于Javascript将PascalCase转换为underscore_case的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!