Chuyển đổi chuỗi thành camelCase: từ đầu viết thường, các từ sau viết hoa chữ cái đầu, loại bỏ khoảng trắng.
Ví dụ
function toCamelCase(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, (match, index) => {
if (match === ' ') return ''; // Bỏ khoảng trắng
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}
console.log(toCamelCase("Add two variables")); // addTwoVariables
console.log(toCamelCase("hello world test")); // helloWorldTest
Cách chạy
node demo.js
Kết quả
addTwoVariables
helloWorldTest
Giải thích Regex: (?:^\w|[A-Z]|\b\w|\s+) khớp: ký tự đầu chuỗi, chữ hoa, ký tự đầu từ (word boundary), hoặc khoảng trắng.
Cách đơn giản hơn:
const toCamelCase = str => str
.toLowerCase()
.split(' ')
.map((w, i) => i === 0 ? w : w[0].toUpperCase() + w.slice(1))
.join('');