Skip to content

String transformations

Robert Biro edited this page Oct 12, 2016 · 1 revision

The .transform() function transforms strings between snake_case, camelCase and TitleCase. It can also transform a whole array of strings, or even the property names of a passed object. Returns the processed input.

Mangler.transform(input, options)
  • input is the string, object or array to transform.
  • options is an object with optional parameters. If a string is provided, it is taken as the to option.

Options:

  • to is the target transformation as string, defaults to '_', meaning snake_case.
  • from is the source transformation, defaults to 'auto' and it tries to break the input into words automatically.
  • ignore is a string or array of strings to skip during processing.
// By default, auto-detects source transform
// These both return 'FooBarBaz'
Mangler.transform('foo_bar_baz', 'title');
Mangler.transform('foo_barBaz', 'title');

// You can specify source and target transforms to avoid guess-work
// This example ignores the primary snake_case detection
// Returns 'Foo_barBaz'
Mangler.transform('foo_barBaz', { from: 'camel', to: 'title' });

// When processing multiple strings, you can set an ignore list
var o = { one: 1, two: 2, three: 3 };
Mangler.transform(o, { to: 'upper_', ignore: ['two'] });
// returns o, which is now: { ONE: 1, two: 2, THREE: 3 }

It supports the following transformations:

  • _ is the default sNake_cAse transformation.
  • upper_ is ALL_UPPERCASE_SNAKE_CASE
  • lower_ is all_lowercase_snake_case
  • title is CapitalisedTitleCase
  • camel is usualCamelCase

In addition, you can replace _ with a delimiter of your choice, for example 'upper.' will be ALL.UPPERCASE.DOT.DELIMITED.

Tokenize

The .tokenize() helper function breaks strings into words/tokens and returns an array of strings. By default it tries to auto-detect the source transformation that is used.

Mangler.tokenize(string, from)
  • string is the source string to break into tokens
  • from is the optional source transformation, defaults to 'auto'

Rename

The .rename() function changes strings or object property names using a dictionary. If you pass a string, it returns the corresponding entry in the dictionary, or the original string if not found. If you pass an object, it renames the matching object properties from the dictionary and returns the object. If you pass an array, it renames all elements and returns the processed array as result.

The dictionary is a simple JavaScript object containing the string pairs to change.

array = ['one', 'two', 'three'];

object = {
	one: 1,
	two: 2,
	three: 3
};

dict = {
	'one' : 'ONE',
	'two' : 'five'
};

Mangler.rename(array, dict);
/*
	array = ['ONE', 'five', 'three']
*/

Mangler.rename(object, dict);
/*
	object = {
		ONE: 1,
		five: 2,
		three: 3
	}
*/

Learning Mangler.js

Optional Modules

Reference

Clone this wiki locally