Mangler.transform() - DarthJDG/Mangler.js GitHub Wiki
Transforms strings or object property names between snake_case, camelCase and TitleCase.
Mangler.transform(object[, options])| Parameter | Type | Default | Description |
|---|---|---|---|
| object | String Object Array.String Array.Object |
String or array of strings to transform. Alternatively an object or array of objects to transform properties of. | |
| options | Object String |
An object with optional method modifiers, or a string to pass as the to option. |
Returns the converted object.
| Property | Type | Default | Description |
|---|---|---|---|
| to | String | '_' |
The type of case to convert to:
|
| from | String | 'auto' |
In addition to 'auto', it can be any of the explicit source formats supported by Mangler.tokenize(). |
| ignore | String Array.String |
[] |
A string or array of strings to ignore and leave as is. |
If object is a string, Mangler.transform() will convert and return it by splitting it into tokens via Mangler.tokenize() using the from option, then putting them back together using the to option. If an array of strings is passed, all string are converted and an array is returned.
When using the default auto option, if there are any underscores in the string, it will be treated as snake case. Otherwise, it will try to find word boundaries by looking at switches between numbers and uppercase and lowercase letters. This means that if you mix camel/title case with underscores, your camel/title case parts will be treated as a single word.
Mangler.transform('ALongIdentifierName'); // = 'a_long_identifier_name'
Mangler.transform('ALongIdentifierName', '_'); // = 'a_long_identifier_name'
Mangler.transform('ALongIdentifierName', 'camel'); // = 'aLongIdentifierName'
Mangler.transform('a_long_identifier_name', 'title'); // = 'ALongIdentifierName'
Mangler.transform('a_long_identifier_name', 'upper_'); // = 'A_LONG_IDENTIFIER_NAME'
Mangler.transform('DontMess_WithTheSnake', 'lower_'); // = 'dontmess_withthesnake'If an object is passed its property names will be transformed, not their values, then the changed object is returned. For arrays of objects all objects will be processed in order, and the array is returned.
o = {
property_one: 'A',
PropertyTwo: 'B',
PROPERTY_THREE: 'C'
};
Mangler.transform(o, { to: 'camel', ignore: 'PROPERTY_THREE' });
/*
o = {
propertyOne: 'A',
propertyTwo: 'B',
PROPERTY_THREE: 'C'
}
*/You can also use a custom single-character delimiter in place of an underscore in '_', 'lower_' and 'upper_':
o = Mangler.transform({ 'use-custom-delimiter': 'value' }, { from: '-', to: 'upper#' });
/*
o = {
'USE#CUSTOM#DELIMITER': 'value'
}
*/