javascriptcamelcasingsentencecase

JavaScript space-separated string to camelCase


I've seen plenty of easy ways to convert camelCaseNames to camel Case Names, etc. but none on how to convert Sentence case names to sentenceCaseNames. Is there any easy way to do this in JS?


Solution

  • This should do the trick :

    function toCamelCase(sentenceCase) {
        var out = "";
        sentenceCase.split(" ").forEach(function (el, idx) {
            var add = el.toLowerCase();
            out += (idx === 0 ? add : add[0].toUpperCase() + add.slice(1));
        });
        return out;
    }
    

    Explanation: