【问题标题】:Javascript/jQuery: Split camelcase string and add hyphen rather than spaceJavascript/jQuery:拆分驼峰字符串并添加连字符而不是空格
【发布时间】:2012-02-15 20:27:06
【问题描述】:

我想这是正则表达式的多部分情况,但是如何将驼峰式字符串在大写字母处拆分为小写字母,然后在每个新字符串之间添加连字符?

例如:

这个字符串

会变成:

这个字符串

【问题讨论】:

  • 在你的例子中,你没有保留大写字母,你的意思是this-String吗?
  • 我认为@user1048007 想保留大写字母,但要保留小写。
  • Wouter 是正确的。它应该以小写结尾。

标签: javascript regex split camelcasing


【解决方案1】:

尝试类似:

var myStr = 'thisString';

myStr = myStr.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();

【讨论】:

  • 我认为您需要 .toLowerCase,但无论哪种方式我都得到 -thisstring
  • 可能想在此处添加 /g:myStr.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
  • 太棒了!这是 CoffeeScript Polyfill: String::toDash ?= -> @replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
【解决方案2】:

回答晚了,但此解决方案适用于单个字母为驼峰式的情况。

'thisIsATest'.replace(/([a-zA-Z])(?=[A-Z])/g, '$1-').toLowerCase();  // this-is-a-test

【讨论】:

    【解决方案3】:

    尝试以下方法:

    var token = document.getElementsByTagName('strong')[0].innerHTML,
        replaced = token.replace(/[a-z][A-Z]/g, function(str, offset) {
           return str[0] + '-' + str[1].toLowerCase();
        });
    
    alert(replaced);
    

    示例 - http://jsfiddle.net/7DV6A/2/

    字符串replace函数的文档:

    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

    【讨论】:

      【解决方案4】:
      String.prototype.camelCaseToDashed = function(){
        return this.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
      }
      // Usage
      "SomeVariable".camelCaseToDashed();
      

      【讨论】:

        【解决方案5】:

        我不知道为什么所有这些解决方案都如此复杂,但我发现这已经足够了:

        function camelCaseToDash(input){ 
             // replace Capital letter with the letter + a dash: '-', then lowercase everything.
             return input.replace(/([A-Z])/g, '-$1').toLowerCase(); 
        }    
        
        //or, using a callback function, directly lowercasing.
        function camelCaseToDashCallback(input){
             //replace capital letter with lowercase variant + a dash '-'.
             return input.replace(/([A-Z])/g, (x)=> "-"+ x.toLowerCase());
        }    
        

        通常选项 1 更快:https://jsfiddle.net/4557z/17/

        【讨论】:

          猜你喜欢
          • 2021-10-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-13
          • 2011-01-08
          • 1970-01-01
          • 2011-01-26
          相关资源
          最近更新 更多