【字符串】驼峰命名与横线命名的转换

831 阅读1分钟

驼峰  ---> 横线

骆驼命名规则的字符串转换成使用短横线命名法的字符串, 并且全小写。

例如: 'getElementById' => 'get-element-by-id'

方法1:正则表达式

function getKebabCase(str) {
  let temp = str.replace(/[A-Z]/g, function (i) {
    return '-' + i.toLowerCase();
  });
  if (temp.slice(0, 1) === '-') {
    temp = temp.slice(1); //如果首字母是大写,执行replace时会多一个_,需要去掉
  }
  return temp;
}
console.log(getKebabCase('getElementById')); // get-element-by-id

方法2:reduce方法

function getKebabCase(prev, cur, index, array) {
  if (/[A-Z]/.test(cur)) {
    cur = cur.toLowerCase();
    if (index === 0) {
      return prev + cur;
    } else {
      return prev + '-' + cur;
    }
  } else {
    return prev + cur;
  }
}

function toKebabCase(arr) {
  if (typeof arr === 'string') {
    arr = arr.split('');
  }
  return arr.reduce(getKebabCase, '');
}

let s = 'getElementById';
let test1 = toKebabCase(s); // get-element-by-id
let test2 = [].reduce.call(s, getKebabCase, ''); // get-element-by-id
console.log(test1, test2);

方法3:利用数组方法

function getKebabCase(str) {
  let arr = str.split('');
  let result = arr
    .map((item) => {
      if (item.toUpperCase() === item) {
        return '-' + item.toLowerCase();
      } else {
        return item;
      }
    })
    .join('');
  return result;
}
console.log(getKebabCase('getElementById')); // get-element-by-id

横线 ---> 驼峰

短横线命名规则的字符串转换成使用驼峰命名法的字符串。

例如: 'get-element-by-id' => 'getElementById'

方法1: 正则表达式

const s = 'get-element-by-id ';
function getCamelCase(str) {
  return str.replace(/-([a-z])/g, function (all, i) {
    return i.toUpperCase();
  });
}

console.log(getCamelCase(s)); // getElementById

方法2: 利用数组方法

const s = 'get-element-by-id';
function getCamelCase(str) {
  let arr = str.split('-').map((item, index) => {
    if (index === 0) {
      return item;
    } else {
      return item[0].toUpperCase() + item.slice(1);
    }
  });
  return arr.join('');
}
console.log(getCamelCase(s)); // getElementById