4

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;
    }
    
VisioN
  • 143,310
  • 32
  • 282
  • 281
Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125
  • 2
    This is your 12th question (in addition to 17 answers), you should be correctly formatting things by now. When you were typing your question, there was this handy **How to Format** box to the right. There was also a preview area underneath. – T.J. Crowder Dec 05 '12 at 09:49
  • Whoops! That was my mistake. I'm aware of code formatiing, but I must remember to add new line at top of code before replacing all with "\n " – Ghoul Fool Dec 05 '12 at 09:56

3 Answers3

19

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"
);
VisioN
  • 143,310
  • 32
  • 282
  • 281
3

Change the first line of your function to

var spacedCamel = str.replace(/([A-Z])/g, " $1");
garyh
  • 2,782
  • 1
  • 26
  • 28
2

The algorithm to this is as follows:

  1. Add space character to all uppercase characters.
  2. Trim all trailing and leading spaces.
  3. Uppercase the first character.

Javascript code:

function camelToSpace(str) {
    //Add space on all uppercase letters
    var result = str.replace(/([A-Z])/g, ' $1').toLowerCase();
    //Trim leading and trailing spaces
    result = result.trim();
    //Uppercase first letter
    return result.charAt(0).toUpperCase() + result.slice(1);
}

Refer to this link