将字符串转换为匹配

5年以前  |  阅读数:362 次  |  编程语言:JavaScript 

将字符串转换为匹配。

使用replace()可删除下划线、连字符和空格, 并将单词转换为匹配。

const toCamelCase = str =>
str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) =>  p2 ? p2.toUpperCase() : p1.toLowerCase());
// toCamelCase("some_database_field_name") -> 'someDatabaseFieldName'
// toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized'
// toCamelCase("some-javascript-property") -> 'someJavascriptProperty'
// toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens'

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8