JavaScript: regex CamelCase to Sentence

只谈情不闲聊 提交于 2019-12-04 16:03:09

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"
);

Change the first line of your function to

var spacedCamel = str.replace(/([A-Z])/g, " $1");

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!