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)?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With