add camelize and decamelize.

This commit is contained in:
gnipbao
2017-12-16 21:24:29 +08:00
parent c286d55182
commit b343a63d67
3 changed files with 35 additions and 0 deletions

17
snippets/camelize.md Normal file
View File

@ -0,0 +1,17 @@
### Camelize
Camelize a string, cutting the string by multiple separators like
hyphens, underscores and spaces.
```js
/**
* @param {str} string str to camelize
* @return string Camelized text
*/
const camelize = str => str.replace(/^([A-Z])|[\s-_]+(\w)/g,
(match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase());
// camelize("some_database_field_name") -> 'someDatabaseFieldName'
// camelize("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized'
// camelize("some-javascript-property") -> 'someJavascriptProperty'
// camelize("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens'
```

16
snippets/decamelize.md Normal file
View File

@ -0,0 +1,16 @@
### decamelize
Decamelizes a string with/without a custom separator (underscore by default).
```js
const decamelize = (str, separator) => {
separator = typeof separator === 'undefined' ? '_' : separator;
return str
.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
.toLowerCase();
}
// decamelize('someDatabaseFieldName', ' ') -> 'some database field name'
// decamelize('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized'
// decamelize('someJavascriptProperty', '_') -> 'some_javascript_property'
```