【问题标题】:Convert sentence or camelCase word to spinal-case将句子或 camelCase 单词转换为脊柱大小写
【发布时间】:2016-09-14 13:29:49
【问题描述】:

我正在尝试将句子格和驼峰格转换为脊柱格。

我可以通过在每个大写字母前添加一个空格来更改驼峰式大小写,但是当我将它应用于空格后带有大写字母的句子时,我会得到额外的间距。

到目前为止,这是我的功能:

function spinalCase(str) {
    var noCamel = str.replace(/([A-Z])/g, ' $1');
    var newStr = noCamel.replace(/\s|_/g, "-");
    return newStr.toLowerCase();
}

spinalCase("makeThisSpinal"); //returns make-this-spinal
spinalCase("Make This Spinal"); //returns -make--this--spinal

【问题讨论】:

  • 你能强调一些你希望这个函数做什么的例子吗?我将第二个示例视为您想要的东西,而不是您试图避免的东西,我感到困惑。
  • 你可以用这个来代替你的var newStr - var newStr = noCamel.replace(/\s+|_+/g, "-");它将消除额外的空格,但您必须考虑“特殊情况”,例如第一个单词中的大写字母

标签: javascript regex


【解决方案1】:

获取 lodash,具体来说,https://lodash.com/docs#kebabCase

_.kebabCase('makeThisSpinal') // make-this-spinal
_.kebabCase('Even Sentences Work') // even-sentences-work

【讨论】:

    【解决方案2】:

    代替:

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

    试试:

    var noCamel = str.replace(/(\B[A-Z])/g, ' $1');
    

    【讨论】:

    【解决方案3】:

    这是因为您将所有大写字母替换为空格及其小写字母。所以在你的句子中,thisspinal 之前有两个空格。

    您可以做的是将所有大写字母替换为"-$1",然后删除字符串中的所有空格。

    【讨论】:

      【解决方案4】:
      function spinalCase(str) {
          var noCamel = str.replace(/([a-z](?=[A-Z]))/g, '$1 ')
          var newStr = noCamel.replace(/\s|_/g, "-");
          return newStr.toLowerCase();
      }
      
      spinalCase("makeThisSpinal"); //returns make-this-spinal
      spinalCase("Make This Spinal"); //returns -make-this-spinal
      

      您应该使用str.replace(/([a-z](?=[A-Z]))/g, '$1 '),而不是str.replace(/([A-Z])/g, ' $1') 用于驼峰式拆分,这将分隔每个单词而不考虑大小写。

      【讨论】:

        【解决方案5】:

        这是我的解决方案,也许你会发现它很好的参考:

        function spinalCase(str) {
          var newStr = str[0];
        
          for (var j = 1; j < str.length; j++) {
            // if not a letter make a dash
            if (str[j].search(/\W/) !== -1 || str[j] === "_") {
              newStr += "-";
            }
            // if a Capital letter is found 
            else if (str[j] === str[j].toUpperCase()) {
              // and preceded by a letter or '_'
              if (str[j-1].search(/\w/) !== -1 && str[j-1] !== "_") {
                // insert '-' and carry on
                newStr += "-";
                newStr += str[j];
              }
              else {
                newStr += str[j];
              }
            }
            else {
                newStr += str[j];
            }
          }
        
          newStr = newStr.toLowerCase();
          return newStr;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-10-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-06
          • 2021-08-14
          • 2019-06-15
          • 1970-01-01
          相关资源
          最近更新 更多