Search code examples
javascriptregexcamelcasing

JavaScript: regex CamelCase to Sentence


I've found this example to change CamelCase to Dashes. I've modified to code to change CamelCase to Sentencecase with spaces instead of dashes. It works fine but not for one word letters, like "i" and "a". Any ideas how to incorporate that as well?

  • thisIsAPain --> This is a pain

    var str = "thisIsAPain"; 
    str = camelCaseToSpacedSentenceCase(str);
    alert(str)
    
    function camelCaseToSpacedSentenceCase(str)
    {
        var spacedCamel = str.replace(/\W+/g, " ").replace(/([a-z\d])([A-Z])/g, "$1 $2");
        spacedCamel = spacedCamel.toLowerCase();
        spacedCamel = spacedCamel.substring(0,1).toUpperCase() + spacedCamel.substring(1,spacedCamel.length)
        return spacedCamel;
    }
    

Solution

  • The very last version:

    "thisIsNotAPain"
        .replace(/^[a-z]|[A-Z]/g, function(v, i) {
            return i === 0 ? v.toUpperCase() : " " + v.toLowerCase();
        });  // "This is not a pain"
    

    The old solution:

    "thisIsAPain"
        .match(/^(?:[^A-Z]+)|[A-Z](?:[^A-Z]*)+/g)
        .join(" ")
        .toLowerCase()
        .replace(/^[a-z]/, function(v) {
            return v.toUpperCase();
        });  // "This is a pain"
    

    console.log(
        "thisIsNotAPain"
            .replace(/^[a-z]|[A-Z]/g, function(v, i) {
                return i === 0 ? v.toUpperCase() : " " + v.toLowerCase();
            })  // "This is not a pain" 
    );
    
    console.log(
        "thisIsAPain"
            .match(/^(?:[^A-Z]+)|[A-Z](?:[^A-Z]*)+/g)
            .join(" ")
            .toLowerCase()
            .replace(/^[a-z]/, function(v) {
                return v.toUpperCase();
            })  // "This is a pain"
    );