JavaScript(js)驼峰命名与中横线命名装换(camelCase<->kebabCase)

1.驼峰命名=>中横线命名

function kebabCase(str) {
  const hyphenateRE = /([^-])([A-Z])/g;
  return str
    .replace(hyphenateRE, '$1-$2')
    .replace(hyphenateRE, '$1-$2')
    .toLowerCase();
}
 
kebabCase("aBXC")

//"a-b-x-c"

2.驼峰命名<=中横线命名

function camelCase(name) {
  const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  const MOZ_HACK_REGEXP = /^moz([A-Z])/;
  return name.replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
    return offset ? letter.toUpperCase() : letter;
  }).replace(MOZ_HACK_REGEXP, 'Moz$1');
}
camelCase("n-ww-m") 
//"nWwM"
camelCase("-n-ww-m")
//"nWwM"

你可能感兴趣的:(JavaScript(js)驼峰命名与中横线命名装换(camelCase<->kebabCase))