From ec407bae9147ec2bb33353dd3d0b9cdec8c49cdb Mon Sep 17 00:00:00 2001 From: gnipbao Date: Sat, 16 Dec 2017 21:24:29 +0800 Subject: [PATCH] add camelize and decamelize. --- snippets/camelize.md | 17 +++++++++++++++++ snippets/decamelize.md | 16 ++++++++++++++++ tag_database | 2 ++ 3 files changed, 35 insertions(+) create mode 100644 snippets/camelize.md create mode 100644 snippets/decamelize.md diff --git a/snippets/camelize.md b/snippets/camelize.md new file mode 100644 index 000000000..937a974e8 --- /dev/null +++ b/snippets/camelize.md @@ -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' +``` diff --git a/snippets/decamelize.md b/snippets/decamelize.md new file mode 100644 index 000000000..ab5ac6fa7 --- /dev/null +++ b/snippets/decamelize.md @@ -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' +``` diff --git a/tag_database b/tag_database index b2535a484..aed0ec9d8 100644 --- a/tag_database +++ b/tag_database @@ -5,6 +5,7 @@ array-intersection:array array-union:array average-of-array-of-numbers:array bottom-visible:browser +camelize:string capitalize-first-letter-of-every-word:string capitalize-first-letter:string chain-asynchronous-functions:function @@ -15,6 +16,7 @@ compact:array count-occurrences-of-a-value-in-array:array current-URL:browser curry:function +decamelize:string deep-flatten-array:array distance-between-two-points:math divisible-by-number:math