Merge pull request #343 from kriadmin/master

[UPDATE] toCamelCase and toSnakeCase
This commit is contained in:
Angelos Chalaris
2017-12-25 01:11:26 +02:00
committed by GitHub
2 changed files with 17 additions and 4 deletions

View File

@ -5,8 +5,15 @@ Converts a string to camelcase.
Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase. Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
```js ```js
const toCamelCase = str => const toCamelCase = str => {
str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase()); 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_database_field_name") -> 'someDatabaseFieldName'
// toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' // toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized'
// toCamelCase("some-javascript-property") -> 'someJavascriptProperty' // toCamelCase("some-javascript-property") -> 'someJavascriptProperty'

View File

@ -5,8 +5,14 @@ Converts a string to snakecase.
Use `replace()` to add underscores before capital letters, convert `toLowerCase()`, then `replace()` hyphens and spaces with underscores. Use `replace()` to add underscores before capital letters, convert `toLowerCase()`, then `replace()` hyphens and spaces with underscores.
```js ```js
const toSnakeCase = str => const toSnakeCase = str =>{
str.replace(/(\w)([A-Z])/g, '$1_$2').replace(/[\s-_]+/g, '_').toLowerCase(); 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.toLowerCase();
});
return arr.join('_')
}
// toSnakeCase("camelCase") -> 'camel_case' // toSnakeCase("camelCase") -> 'camel_case'
// toSnakeCase("some text") -> 'some_text' // toSnakeCase("some text") -> 'some_text'
// toSnakeCase("some-javascript-property") -> 'some_javascript_property' // toSnakeCase("some-javascript-property") -> 'some_javascript_property'