Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แปลงสตริงคั่นขีดกลางเป็น camelCase ใน JavaScript

สมมติว่าเรามีสตริงที่มีคำคั่นด้วยขีดกลางดังนี้:

const str = 'this-is-an-example';

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงแบบนี้และแปลงเป็น camelCase string

สำหรับสตริงข้างต้น ผลลัพธ์ควรเป็น:

const output = 'thisIsAnExample';

โค้ดสำหรับเรื่องนี้จะเป็น:

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

ผลลัพธ์บนคอนโซล:

thisIsAnExample