ใช้ Regex แทนที่ตัวอักษรแรกของแต่ละคำให้เป็นพิมพ์ใหญ่ (ยกเว้นคำแรก) และลบช่องว่าง
ตัวอย่างโค้ด
function convertStringToCamelCase(sentence) {
return sentence.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(camelCaseMatch, i) {
if (+camelCaseMatch === 0) return "";
return i === 0 ? camelCaseMatch.toLowerCase() : camelCaseMatch.toUpperCase();
});
}
console.log(convertStringToCamelCase("Add two variables"));
วิธีรันโปรแกรม
ใช้คำสั่ง node fileName.js (เช่น node demo104.js)
ผลลัพธ์
addTwoVariables