Use the built-in string, number, date and array helpers
Total.js adds a set of methods to the JavaScript built-ins. They are available everywhere in the app, so they are worth knowing before you write a helper of your own. The ones below are exercised by the example.
String: slug([max]) makes a URL-safe text (lowercase, no accents or symbols); format(a, b) replaces {0}, {1}; encode() / decode() escape and restore HTML; padLeft(length, char) / padRight(); parseInt2() and parseFloat2() read a number out of a text and return 0 when there is none; isEmail(), isURL() and isJSON() validate; parseJSON() parses JSON and returns null on error; md5(), sha1() and sha256() return hex hashes; capitalize() upper-cases the first letter of every word.
Number: format(decimals, thousands, decimal), for example (1234567.891).format(2) gives 1 234 567.89.
Date: format('yyyy-MM-dd HH:mm'), add('1 day') and diff(date, 'days').
Array: take(n) and skip(n), first() and last(), trim() (trims the texts and removes the empty ones), findItem(field, value) and findIndex(field, value), remove(value) (removes every match and returns the array), group(field) (returns [{ name, items }]) and quicksort(field).
Objects: U.extend(target, source) merges source into target and returns it; U.clone(object) makes a deep copy.
exports.install = function() {
ROUTE('GET /utils/', utils);
};
function utils($) {
var items = [{ type: 'a', n: 1 }, { type: 'b', n: 2 }, { type: 'a', n: 3 }];
var original = { a: { b: 1 } };
var copy = U.clone(original);
copy.a.b = 2;
$.json({
slug: 'Hello Wörld & Co!'.slug(),
slugmax: 'Hello brave new world'.slug(11),
format: '{0} has {1} items'.format('Ann', 3),
encode: '<a href="x">&</a>'.encode(),
decode: '<b>'.decode(),
pad: ['7'.padLeft(3, '0'), '7'.padRight(3, '0')],
numbers: ['abc12x'.parseInt2(), '3,5kg'.parseFloat2(), 'none'.parseInt2()],
is: ['a@b.cz'.isEmail(), 'nope'.isEmail(), 'https://totaljs.com'.isURL(), '{"a":1}'.isJSON(), 'abc'.isJSON()],
json: ['{"a":1}'.parseJSON(), 'not json'.parseJSON()],
md5: 'abc'.md5(),
sha1: 'abc'.sha1(),
capitalize: 'hello big world'.capitalize(),
number: [(1234567.891).format(2), (1234567.891).format(2, ' ', ',')],
date: [new Date(2026, 0, 5, 9, 7).format('yyyy-MM-dd HH:mm'), new Date(2026, 0, 31).add('1 day').format('yyyy-MM-dd'), new Date(2026, 0, 5).diff(new Date(2026, 0, 1), 'days')],
take: [[1, 2, 3, 4, 5].take(2), [1, 2, 3, 4, 5].skip(3), [1, 2, 3].first(), [1, 2, 3].last()],
trim: ['a', '', ' b '].trim(),
find: [[{ id: 1 }, { id: 2 }].findItem('id', 2), [{ id: 1 }, { id: 2 }].findIndex('id', 2)],
remove: [1, 2, 3, 2].remove(2),
group: items.group('type'),
sort: [{ n: 'b' }, { n: 'a' }].quicksort('n'),
extend: U.extend({ a: 1 }, { b: 2 }),
clone: [original.a.b, copy.a.b]
});
}