intruxxer
6/19/2017 - 3:13 PM

To convert string to camel case in javascript.

To convert string to camel case in javascript.

//Original 
//e.g. my life is good => MyLifeIsGood
function toCamelCase(str) {
    return str.toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) {
        return match.charAt(match.length-1).toUpperCase();
    });
}

//Forked: Capable to Handle > 1 word/Phrase
//e.g. my life is good => My Life Is Good
function toCamelCase(str) {
    var camelized = "";
    var splitted  = str.split(" ");
    var splitted_camelized;
    for (i = 0; i < splitted.length; i++) { 
        splitted_camelized = splitted[i].toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) {
            return match.charAt(match.length-1).toUpperCase();
        });

        if(i == splitted.length - 1)
            camelized = camelized + splitted_camelized + " ";
        else
            camelized = camelized + splitted_camelized + " ";
    }
    return camelized;
}