Looking at your code, you can achieve it with only two replace
calls:(查看您的代码,只需两个replace
调用即可实现:)
function camelize(str) {
return str.replace(/(?:^w|[A-Z]|w)/g, function(word, index) {
return index == 0 ? word.toLowerCase() : word.toUpperCase();
}).replace(/s+/g, '');
}
camelize("EquipmentClass name");
camelize("Equipment className");
camelize("equipment class name");
camelize("Equipment Class Name");
// all output "equipmentClassName"
Edit: Or in with a single replace
call, capturing the white spaces also in the RegExp
.(编辑:或通过单个replace
调用,也可以在RegExp
捕获空白。)
function camelize(str) {
return str.replace(/(?:^w|[A-Z]|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();
});
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…