diff --git a/snippets/convert-string-from-camelcase.md b/snippets/convert-string-from-camelcase.md new file mode 100644 index 000000000..969be904d --- /dev/null +++ b/snippets/convert-string-from-camelcase.md @@ -0,0 +1,13 @@ +### Convert string from camelcase + +Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase. +Omit the scond argument to use a default separator of '_'. + +```js +const fromCamelCase = (str, separator = '_') => + 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/snippets/convert-string-to-camelcase.md b/snippets/convert-string-to-camelcase.md new file mode 100644 index 000000000..ba34a6835 --- /dev/null +++ b/snippets/convert-string-to-camelcase.md @@ -0,0 +1,12 @@ +### Convert string to camelcase + +Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase. + +```js +const toCamelCase = 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/tag_database b/tag_database index 3999b7f30..927d17274 100644 --- a/tag_database +++ b/tag_database @@ -10,6 +10,7 @@ array-without:array array-zip:array average-of-array-of-numbers:array bottom-visible:browser +convert-string-to-camelcase:string capitalize-first-letter-of-every-word:string capitalize-first-letter:string chain-asynchronous-functions:function @@ -22,6 +23,7 @@ compose-functions:function count-occurrences-of-a-value-in-array:array current-URL:browser curry:function +convert-string-from-camelcase:string deep-flatten-array:array distance-between-two-points:math divisible-by-number:math