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

前端 未结 5 1258
故里飘歌
故里飘歌 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: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/

提交回复
热议问题