JavaScript:regex CamelCase to Sentence

时间:2012-12-05 09:45:39

标签: javascript regex camelcasing

我发现this example将CamelCase更改为Dashes。 我修改了代码,用空格而不是短划线将CamelCase更改为Sentencecase。它工作正常,但不是一个字母,如“我”和“一个”。任何想法如何融入其中?

  • thisIsAPain - >这是一种痛苦

    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;
    }
    

3 个答案:

答案 0 :(得分:14)

最后一个版本:

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

旧解决方案:

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

答案 1 :(得分:3)

将功能的第一行更改为

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

答案 2 :(得分:2)

对此的算法如下:

  
      
  1. 为所有大写字符添加空格字符。
  2.   
  3. 修剪所有尾随和前导空格。
  4.   
  5. 大写第一个字符。
  6.   

Javascript代码:

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

请参阅此link