Javascript/jQuery: Split camelcase string and add hyphen rather than space

前端 未结 5 1247
故里飘歌
故里飘歌 2020-12-23 11:29

I would imagine this is a multiple part situation with regex, but how would you split a camelcase string at the capital letters turning them in to lowercase letters, and the

相关标签:
5条回答
  • 2020-12-23 11:51

    Try the following:

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

    Example - http://jsfiddle.net/7DV6A/2/

    Documentation for the string replace function:

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

    0 讨论(0)
  • 2020-12-23 11:56

    I don't know why all these solutions are so complex but i simply found this to be enough:

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

    generally option 1 is faster though: https://jsfiddle.net/4557z/17/

    0 讨论(0)
  • 2020-12-23 12:00

    Late to answer, but this solution will work for cases where a single letter is camel cased.

    'thisIsATest'.replace(/([a-zA-Z])(?=[A-Z])/g, '$1-').toLowerCase();  // this-is-a-test
    
    0 讨论(0)
  • 2020-12-23 12:03
    String.prototype.camelCaseToDashed = function(){
      return this.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
    }
    // Usage
    "SomeVariable".camelCaseToDashed();
    
    0 讨论(0)
  • 2020-12-23 12:07

    Try something like:

    var myStr = 'thisString';
    
    myStr = myStr.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
    
    0 讨论(0)
提交回复
热议问题