2

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.

Sunny
  • 9,245
  • 10
  • 49
  • 79

1 Answers1

7

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

Leon Adler
  • 2,993
  • 1
  • 29
  • 42
  • 2
    This is not "greedy" matching, it's "global" matching. –  Nov 19 '15 at 04:44
  • @LeanAdler. Yes it works as expected. Does NOT convert all uppercase letters as in MY_CONSTANT_CONFIG which is nice though not specified by me. Conversion would have made it unreadable. Also, handles multiple occurrences as in xx_xAc_atx9. I am accepting the answer. Can you modify it slightly to also handle cases such as xxx_9xxx where only the _ will be removed? I have edited my question as the example was incorrect. Thanks! – Sunny Nov 19 '15 at 05:09
  • 1
    @Samir just add the allowed characters in the class. i.e: change `[a-z]` to `[a-z0-9]` – Mariano Nov 19 '15 at 05:12
  • yes, or explicitly exclude the characters you do *not* want to match for: `[^A-Z]` – Leon Adler Nov 19 '15 at 05:13
  • @Mariano—perhaps simpler is `\w`. – RobG Nov 19 '15 at 05:35
  • 1
    @RobG `\w` includes `_` and uppercase letters, and the OP stated it shouldn't match. – Mariano Nov 19 '15 at 05:36