如何使用 javascript 正则表达式将字符串转换为驼峰式大小写?
EquipmentClass 名称
或
设备类名
或设备类名
或设备类名
都应该变成:equipmentClassName
。
最佳答案
查看您的代码,只需两次 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, '');
}
camelize("EquipmentClass name");
camelize("Equipment className");
camelize("equipment class name");
camelize("Equipment Class Name");
// all output "equipmentClassName"
编辑:或者使用单个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();
});
}
关于javascript - 将任何字符串转换为驼峰大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2970525/