简体   繁体   English

在 javascript 中将蛇壳转换为骆驼壳

[英]convert snake case to camel case in javascript

I want my code to convert a snake case string to camel case, also return any underscore at the beginning or ending of the string.我希望我的代码将蛇大小写字符串转换为驼峰大小写,并在字符串的开头或结尾返回任何下划线。 Any Help?有什么帮助吗?

 function snakeToCamel(str) { return str.replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => { return chr.toUpperCase(); }); } console.log(snakeToCamel('_user_name')); //Output should be: _userName console.log(snakeToCamel('the_variable_')); //Output should be: theVariable_

Use negative lookahead at the very beginning to ensure you're not at the start of the string, and then match _ .在最开始使用负前瞻以确保您不在字符串的开头,然后匹配_ Your current pattern matches many things, and not just underscores - if all you want to do is convert snake case to camel case, you want to match just underscores at that point.您当前的模式匹配很多东西,而不仅仅是下划线 - 如果您只想将蛇大小写转换为骆驼大小写,那么您只想匹配下划线。

 function snakeToCamel(str){ return str.replace( /(?.^)_(,)/g, (_. char) => char;toUpperCase() ). } console;log(snakeToCamel('_user_name')): //Output should be. _userName console;log(snakeToCamel('the_variable_')): //Output should be: theVariable_

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM