Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making the camel happy in camel case conversion

I have written the function for camel-casing strings (the requirement is to kick-up the characters in the beginning of a word and after each hyphen, which is targeting personal names).

function sadCamelize(input) {
  return input.toLowerCase().replace(/([-\s])(.)/g,
    function(match, separator, starter) {
      return separator + starter.toUpperCase();
  });
}

Now, I'd like to make my camel happy so that even the first character of the string (not succeeding space nor hyphen), will be kicked-up. Id est, instead of:

HONKA-HONKA -> honka-Honka

I'd like to get

HONKA-HONKA -> Honka-Honka

At the moment I'm stuck, probably due to annoyance. All camels are depressed and so an I. Also - what is the correct nomenclature of what I call sad/happy camel (the head down/up)?

like image 422
Konrad Viltersten Avatar asked Oct 09 '13 08:10

Konrad Viltersten


1 Answers

function happyCamelize(str) {
    return str.replace(/([a-z])([a-z]+)/gi, function(_, $1, $2) {
        // _: The entire matched string. not used here.
        // $1: The first group. The first alphabet.
        // $2: The second group. The rest alphabets.
        return $1.toUpperCase() + $2.toLowerCase();
    });
}

Example:

happyCamelize('HONKA-HONKA') // "Honka-Honka"

NOTE This code will not change single length word.

happyCamelize('h') // => "h"
happyCamelize('H') // => "H"

If you want to also camelize single length word, use /([a-z])([a-z]*)/gi.

like image 53
falsetru Avatar answered Oct 03 '22 16:10

falsetru