diff --git a/snippets/toCamelCase.md b/snippets/toCamelCase.md index 20e3821e2..8b367b929 100644 --- a/snippets/toCamelCase.md +++ b/snippets/toCamelCase.md @@ -5,8 +5,15 @@ Converts a 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()); +const toCamelCase = str => { +let regex = rx = /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g; + let arr = str.match(regex); + arr = arr.map(x =>{ + return x.slice(0,1).toUpperCase() + x.slice(1).toLowerCase(); + }); + str = arr.join('') + return str.slice(0,1).toLowerCase() + str.slice(1) + } // toCamelCase("some_database_field_name") -> 'someDatabaseFieldName' // toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' // toCamelCase("some-javascript-property") -> 'someJavascriptProperty' diff --git a/snippets/toSnakeCase.md b/snippets/toSnakeCase.md index 509e228c5..4709f8623 100644 --- a/snippets/toSnakeCase.md +++ b/snippets/toSnakeCase.md @@ -5,13 +5,14 @@ Converts a string to snakecase. Use `replace()` to add underscores before capital letters, convert `toLowerCase()`, then `replace()` hyphens and spaces with underscores. ```js -const toSnakeCase = str => +const toSnakeCase = str =>{ let regex = rx = /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g; let arr = str.match(regex); - arr = arr.forEach(x =>{ - return s.toLowerCase(); + arr = arr.map(x =>{ + return x.toLowerCase(); }); return arr.join('_') + } // toSnakeCase("camelCase") -> 'camel_case' // toSnakeCase("some text") -> 'some_text' // toSnakeCase("some-javascript-property") -> 'some_javascript_property'