简体   繁体   中英

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])?

I am open to using Javascript or any Linux tool. 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.

You can use a Replacement callback :

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)
_ - match the underscore ( duh... )
([az]) - match one lowercase letter and capture in group 1, matches[1]
/.../g - "global" matching, ie replace not only the first but all occurences

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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