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

Chuyển chuỗi sang camelCase trong JavaScript

camelCase: từ đầu tiên lowercase, các từ sau viết hoa chữ cái đầu, không space/punctuation. Ví dụ: "Concurrent hash maps" → "ConcurrentHashMaps".

Implementation

function camelize(str) {
  return str.split(' ')
    .map(word => word.trim())
    .map(word => word[0].toUpperCase() + word.slice(1))
    .join('');
}

console.log(camelize("Concurrent hash maps")); // ConcurrentHashMaps

Biến thể: lowerCamelCase (từ đầu lowercase)

function toLowerCamelCase(str) {
  const words = str.split(' ').map(w => w.trim()).filter(w => w);
  return words[0].toLowerCase() + words.slice(1).map(w => w[0].toUpperCase() + w.slice(1)).join('');
}

console.log(toLowerCamelCase("Concurrent hash maps")); // concurrentHashMaps

Regex one-liner

const camel = str => str.replace(/(?:^\w|[A-Z]|\b\w)/g, (m, i) => i === 0 ? m.toLowerCase() : m.toUpperCase()).replace(/\s+/g, '');