Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Chuyển chuỗi kebab-case sang camelCase - JavaScript

Chuỗi 'this-is-an-example' → 'thisIsAnExample'. Tách theo -, viết hoa chữ cái đầu từ thứ 2 trở đi.

Mã thực hiện

const str = 'this-is-an-example';
const changeToCamel = str => {
  let newStr = '';
  newStr = str.split('-').map((el, ind) => ind && el.length ? el[0].toUpperCase() + el.substring(1) : el).join('');
  return newStr;
};
console.log(changeToCamel(str));

Kết quả

thisIsAnExample