JavaScript 正規表現を使用して文字列をキャメルケースに変換するにはどうすればよいですか?
EquipmentClass name
またはEquipment className
またはequipment class name
またはEquipment Class Name
すべて次のようになりますequipmentClassName
。
ベストアンサー1
コードを見ると、たった 2 回のreplace
呼び出しでこれを実現できます。
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
return index === 0 ? word.toLowerCase() : word.toUpperCase();
}).replace(/\s+/g, '');
}
// all output "equipmentClassName"
console.log(camelize("EquipmentClass name"));
console.log(camelize("Equipment className"));
console.log(camelize("equipment class name"));
console.log(camelize("Equipment Class Name"));
編集:または、 を 1 回の呼び出しで実行しreplace
、 内の空白もキャプチャしますRegExp
。
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}