简体   繁体   English

正则表达式或其他方式在JavaScript中转换为类似驼峰的情况

[英]Regular expression or other way to convert to camel-like case in JavaScript

I have gone through similar posts but none of them handle this specific case. 我已经通过类似的帖子,但没有一个处理这个特定的情况。 I want to convert some old naming conventions to camel-like case. 我想将一些旧的命名约定转换为类似驼峰的情况。 However, I want the conversion to be restricted to only the following: 但是,我希望转换仅限于以下内容:

A string (consisting of alphabets in any case or numbers) followed by an underscore followed by an alphabet should be replaced by the same string followed by the same alphabet but only that alphabet in uppercase. 一个字符串 (在任何情况下由数字或数字组成)后跟一个下划线后跟一个字母表应该被相同的字符串替换,后面跟着相同的字母,但只有大写字母。 Nothing more. 而已。

Some examples: 一些例子:

aXc9tu_muKxx  ->  aXc9tuMuKxx
zdmmpFmxf     ->  zdmmpFmxf //unchanged 
_xfefx        ->  _xfefx    //unchanged
Z_9fefx       ->  Z9fefx    //EDITED after getting answers.

So, if ? 因此,如果 ? in a regular expression meant 1 or more occurrences and [] was used to specify a range of characters, then I would imagine that the source expression would be: ([0-9a-zA-Z])?_([0-9a-zA-Z])? 在正则表达式中意味着出现1次或多次而[]用于指定字符范围,那么我可以想象源表达式将是:([0-9a-zA-Z])?_([0-9a -Za-Z])?

I am open to using Javascript or any Linux tool. 我愿意使用Javascript或任何Linux工具。 I repeat again that the conversion will only involve two characters _ and the letter immediately following it, if indeed it is a letter. 我再次重申,转换只涉及两个字符_和紧随其后的字母,如果它确实是一封信。 The _ will be removed and the letter will be upper-cased. _将被删除,信件将是大写的。 If it is not a letter but a digit, then just the underscore will be removed. 如果它不是字母而是数字,则只删除下划线。

The goal is to move towards camel case but maintain readability of old naming conventions, where readability can be compromised after conversion. 目标是转向骆驼案例,但保持旧命名约定的可读性,转换后可读性可能会受到损害。 For example, THIS_IS_A_CONSTANT does not get altered to THISISACONSTANT. 例如,THIS_IS_A_CONSTANT不会更改为THISISACONSTANT。

You can use a Replacement callback : 您可以使用Replacement回调

function toCamelCase(str) {
  return str.replace(/(?!^)_([a-z])/g, function(matches) {
    return matches[1].toUpperCase();
  });
}

Explanation of the regex: 正则表达式的解释:

(?!^) - do not match at start of string (your "_xfefx" example) (?!^) - 在字符串的开头不匹配(你的"_xfefx"示例)
_ - match the underscore ( duh... ) _ - 匹配下划线( duh ......
([az]) - match one lowercase letter and capture in group 1, matches[1] ([az]) - 匹配一个小写字母并在组1中捕获, matches[1]
/.../g - "global" matching, ie replace not only the first but all occurences /.../g - “全局”匹配,即不仅替换第一次而且替换所有事件

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

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