【问题标题】:JavaScript: regex CamelCase to SentenceJavaScript:正则表达式 CamelCase 到句子
【发布时间】:2012-11-23 02:28:33
【问题描述】:

我已找到 this example 将 CamelCase 更改为破折号。 我已修改代码以将 CamelCase 更改为 Sentencecase,其中包含空格而不是破折号。它工作正常,但不适用于一个单词字母,如“i”和“a”。有什么想法可以将它也纳入其中吗?

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

【问题讨论】:

  • 这是您的第 12 个问题(除了 17 个答案),您现在应该正确格式化内容。当您输入问题时,右侧有一个方便的 如何格式化 框。下面还有一个预览区。
  • 哎呀!那是我的错误。我知道代码格式化,但我必须记得在代码顶部添加新行,然后再用 "\n "

标签: javascript regex camelcasing


【解决方案1】:

最后一个版本:

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

【讨论】:

  • 这样的速度!这是美丽的事情。有朝一日,我希望长出一个更大的大脑并破译这一切。
  • @GhoulFool 我很确定你可以做得更快;)
  • 一天。我只是一个 4 级 RegExp 向导。很快我就会达到 5 级,开始玩单词表,把猫变成蝙蝠
【解决方案2】:

将函数的第一行更改为

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

【讨论】:

    【解决方案3】:

    算法如下:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      • 2012-07-02
      • 2017-04-14
      相关资源
      最近更新 更多