3 回答

TA貢獻1946條經驗 獲得超4個贊
查看您的代碼,只需兩個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();
});
}

TA貢獻1802條經驗 獲得超6個贊
如果有人在使用lodash,則有一個_.camelCase()功能。
_.camelCase('Foo Bar');
// → 'fooBar'
_.camelCase('--foo-bar--');
// → 'fooBar'
_.camelCase('__FOO_BAR__');
// → 'fooBar'

TA貢獻1798條經驗 獲得超3個贊
我剛結束這樣做:
String.prototype.toCamelCase = function(str) {
return str
.replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
.replace(/\s/g, '')
.replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}
我試圖避免將多個replace語句鏈接在一起。在我的函數中有$ 1,$ 2,$ 3的東西。但是這種類型的分組很難理解,而您對跨瀏覽器問題的提及也是我從未想過的。
添加回答
舉報