JavaScript RegExp to CamelCase a hyphened CSS property

后端 未结 6 1484
心在旅途
心在旅途 2021-02-19 12:47

I am trying to change CSS properties like this one.

-moz-border-radius

To the JavaScript CSS property like so.

MozBorderRadius
         


        
6条回答
  •  没有蜡笔的小新
    2021-02-19 13:31

    Another, slightly more flexible answer:

    if (typeof String.prototype.toCamel !== 'function') {
      String.prototype.toCamel = function(){
        return this.replace(/[-_]([a-z])/g, function (g) { return g[1].toUpperCase(); })
      };
    }
    

    Used like this:

    '-moz-border-radius'.toCamel(); // "MozBorderRadius"
    'moz-border-radius'.toCamel(); // "mozBorderRadius"
    'moz_border_radius'.toCamel(); // "mozBorderRadius"
    '_moz_border_radius'.toCamel(); // "MozBorderRadius"
    

提交回复
热议问题