Prototypes
Every method that Total.js adds to String, Number, Date and Array.prototype.
On this page
Methods that Total.js 5 adds to the built-in prototypes String, Number, Date and Array. They are available everywhere once the framework is loaded. The guide Prototypes shows how to use them together with examples; this page is the exact reference.
API
method
str.format(arg0, [arg1], [...])
Replaces numbered placeholders {0}, {1}, ... with the arguments.
str.format(arg0, [arg1], [...])| Parameter | Type | Description |
|---|---|---|
arg0...argN |
Any |
Values for {0}, {1} and so on. |
Returns String The new string.
Each {n} is replaced with the argument at index n. A placeholder whose argument is null or undefined becomes an empty string. Only numbers are allowed inside the braces; use String.args() for named keys.
'Hello {0}, you have {1} messages.'.format('Peter', 5);
// Hello Peter, you have 5 messages.
method
str.args(obj, [encode], [def])
Replaces named placeholders {key} or {{key}} with values of an object.
str.args(obj, [encode], [def])| Parameter | Type | Description |
|---|---|---|
obj |
Object |
The values. |
encode? |
String|Function |
html, json, a function (value, key) or any other string for URL encoding. |
def? |
String |
The text for keys without a value. |
Returns String The new string.
String.arg() is the same method. A placeholder is a key in single or double braces; spaces inside the braces are trimmed. Keys are read directly from obj (no nested paths).
encode changes the output of each value: 'html' encodes it with String.encode(), 'json' writes JSON.stringify(value), any other truthy string uses encodeURIComponent(), and a function (value, key) returns the text itself. When encode is a string it also replaces def: with 'html' or a URL-encoding string, a key without a value becomes the text of encode; with 'json' it becomes undefined. Without encode, a key without a value is left as it is, or replaced with def when you pass one.
var tpl = 'Hello {name}, your order {{ id }} is ready.';
tpl.args({ name: 'Peter', id: 'A100' });
// Hello Peter, your order A100 is ready.
'<b>{name}</b>'.args({ name: '<script>' }, 'html');
// <b><script></b>
method
str.slug([max])
Makes a URL-friendly slug from the text.
str.slug([max])| Parameter | Type | Description |
|---|---|---|
max? |
Number |
The maximum length of the slug. Default: 60 |
Returns String The slug.
The text is trimmed, lowercased and diacritics are removed (toASCII()). Letters, digits and _ are kept; spaces and the characters !"#$%&'()*+,-./ become a single -; other characters are dropped. A trailing - is removed and the result has at most max characters.
When the text contains a character without an ASCII form whose code is above 540 (for example Cyrillic letters, € or an emoji), the whole text is not slugged letter by letter: the method then returns a short hash-based identifier made from the text, so the result is still stable and URL-safe.
' Hello World! Čaute 123 '.slug();
// hello-world-caute-123
'A very long article title'.slug(10);
// a-very-lon
method
str.max(length, [chars])
Shortens the text to a maximum length and adds an ellipsis.
str.max(length, [chars])| Parameter | Type | Description |
|---|---|---|
length |
Number |
The maximum length of the result. |
chars? |
String |
The text appended to a shortened string. Default: '...' |
Returns String The text, shortened when needed.
When the text is longer than length, it is cut so that the result including chars has exactly length characters. Shorter text is returned unchanged.
'Hello world'.max(8); // Hello...
'Hello world'.max(8, '…'); // Hello w…
method
str.capitalize([first])
Capitalizes the first letter of every word, or only of the text.
str.capitalize([first])| Parameter | Type | Description |
|---|---|---|
first? |
Boolean |
Capitalize only the first character. Default: false |
Returns String The new string.
The text is lowercased first. Without arguments every letter after a space, tab or new line becomes uppercase. With first set to true, only the first character is uppercased and the rest stays lowercase.
'hello WORLD'.capitalize(); // Hello World
'hello WORLD'.capitalize(true); // Hello world
method
str.toName()
Cleans a person name: removes digits and symbols, extra spaces and capitalizes words.
str.toName()Returns String The cleaned name.
Only ASCII letters, characters above code 127 (letters with diacritics) and spaces are kept. Repeated spaces are reduced to one, trailing spaces are removed (leading spaces become one space) and the first letter of each word is uppercased. The rest of each word is kept as it is.
'peter sirka 12'.toName();
// Peter Sirka
method
str.encode()
Encodes HTML special characters.
str.encode()Returns String The encoded text.
String.safehtml() is the same method. The characters <, >, ", ' and & are replaced with <, >, ", ' and &. Use it before you put user text into HTML.
'<a href="x">Tom & Jerry</a>'.encode();
// <a href="x">Tom & Jerry</a>
method
str.decode()
Decodes HTML entities back to characters.
str.decode()Returns String The decoded text.
Named entities (<, &, ", ...) and numeric entities (A, A) are replaced with their characters. Unknown named entities stay as they are.
'<b>Tom & Jerry!</b>'.decode();
// <b>Tom & Jerry!</b>
method
str.removeTags()
Removes HTML tags from the text.
str.removeTags()Returns String The text without tags.
Every <...> tag (opening or closing) is removed; the text between tags stays. The result is not HTML-encoded, so encode it with String.encode() when you write it back into HTML.
'<p><b>Hi</b> there</p>'.removeTags();
// Hi there
method
str.padLeft(max, [c])
Pads the text on the left to a length. String.padRight() pads on the right.
str.padLeft(max, [c])| Parameter | Type | Description |
|---|---|---|
max |
Number |
The length of the result. |
c? |
String |
The padding character. Default: ' ' |
Returns String The padded text.
Characters c are added until the text has max characters; longer text is returned unchanged. str.padRight(max, [c]) works the same way on the right side. Both are defined only when the runtime does not already have them.
'5'.padLeft(3, '0'); // 005
'a'.padRight(3, '-'); // a--
method
str.toASCII()
Replaces letters with diacritics by their ASCII form.
str.toASCII()Returns String The text without diacritics.
Letters such as č, á or ü are replaced with c, a and u. Characters without an ASCII form stay as they are.
'Čučoriedka'.toASCII();
// Cucoriedka
method
str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])
Extracts keywords from the text, the most frequent first.
str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])| Parameter | Type | Description |
|---|---|---|
forsearch? |
Boolean |
Normalize the words for search. Default: true |
alternative? |
Boolean |
Shorten words to 80 % of their length. Default: false |
max_count? |
Number |
The maximum number of words to read. Default: 200 |
max_length? |
Number |
The maximum length of a keyword. Default: 20 |
min_length? |
Number |
The minimum length of a keyword. Default: 2 |
Returns Array Unique keywords sorted by frequency.
The text is lowercased and split into words; characters that are not letters or digits are removed from each word. With forsearch (default) diacritics are removed and y becomes i, which makes matching tolerant. alternative keeps only the first 80 % of longer words (a simple stem). Words shorter than min_length or longer than max_length are skipped and at most max_count words are read. The unique words are returned sorted by how often they appear.
For a single normalized search string use str.toSearch(): it lowercases the text, removes diacritics and symbols, replaces y with i and drops repeated letters (hello becomes helo).
'Total.js is a great framework, great!'.toKeywords();
// ['great', 'totaljs', 'is', 'framework']
'Čaute Hello'.toSearch();
// caute helo
method
str.pluralize(zero, one, few, other)
Converts the text to a number and picks a plural form.
str.pluralize(zero, one, few, other)| Parameter | Type | Description |
|---|---|---|
zero |
String |
Text for 0, or all four forms separated by commas. |
one? |
String |
Text for 1. |
few? |
String |
Text for 2 to 4. |
other? |
String |
Text for other numbers. |
Returns String The chosen form.
The text is converted with parseInt() and the result is passed to Number.pluralize().
'3'.pluralize('no items', '# item', '# items', '# items');
// 3 items
method
str.parseInt([def])
Converts the text to a number, with a default for invalid text.
str.parseInt([def])| Parameter | Type | Description |
|---|---|---|
def? |
Number |
The value for text that is not a number. Default: 0 |
Returns Number The number or the default.
The text is trimmed and converted with the unary +, so '10' is 10, '1.5' is 1.5 and '0x10' is 16. When the text is not a number, def is returned (0 when you omit it).
str.parseInt2([def]) finds the first integer anywhere in the text instead ('abc 123' gives 123); str.parseFloat2([def]) does the same for a decimal number and accepts , as the decimal separator.
'10'.parseInt(); // 10
'abc'.parseInt(5); // 5
'Total: 123 EUR'.parseInt2(); // 123
'x 1,5 y'.parseFloat2(); // 1.5
method
str.parseFloat([def])
Converts the text to a decimal number; a comma is accepted as the decimal separator.
str.parseFloat([def])| Parameter | Type | Description |
|---|---|---|
def? |
Number |
The value for text that is not a number. Default: 0 |
Returns Number The number or the default.
The text is trimmed, the first , is replaced with . and the text is converted to a number. When the text is not a number, def is returned (0 when you omit it).
'1,5'.parseFloat(); // 1.5
' 2.25 '.parseFloat(); // 2.25
'n/a'.parseFloat(-1); // -1
method
str.parseBoolean()
Converts the text to a boolean.
str.parseBoolean()Returns Boolean
Returns true for true, 1 and on (case-insensitive) and false for everything else.
'on'.parseBoolean(); // true
'TRUE'.parseBoolean(); // true
'no'.parseBoolean(); // false
method
str.parseDate([format])
Converts the text to a Date.
str.parseDate([format])| Parameter | Type | Description |
|---|---|---|
format? |
String |
A format such as dd/MM/yyyy HH:mm. |
Returns Date The parsed date.
Without format the method understands:
- JSON dates (
2024-05-01T12:30:00.000Z), yyyy-MM-dd,yyyy-MM-dd HH:mm,yyyy-MM-dd HH:mm:ssandyyyy-MM-ddTHH:mm:ss.SSS,d.M.yyyywith an optional time (1.5.2024 08:00),- anything else that
new Date(text)accepts.
The date and time of these forms are read as UTC. Missing parts of the date are taken from today.
With format the digits of the text are read by the positions of yyyy, MM, dd, HH, mm and ss in the format; the other characters of the format only separate the parts. The parts must be written with all their digits (05, not 5). A two-digit year is in the 2000s, and pm in the text adds 12 hours.
'2024-05-01 12:30'.parseDate();
// 2024-05-01T12:30:00.000Z
'1.5.2024'.parseDate();
// 2024-05-01T00:00:00.000Z
'01/05/2024'.parseDate('dd/MM/yyyy');
// 1 May 2024
method
str.parseDateExpiration()
Converts a relative time such as "5 minutes" to a Date in the future.
str.parseDateExpiration()Returns Date The current time plus the given duration.
The text is a list of pairs number unit separated by spaces. Each pair is added to the current time with Date.add(), so all units of Date.add() work (seconds, minutes, hours, days, weeks, months, years and their short forms). Use a negative number for a date in the past.
var expire = '5 minutes'.parseDateExpiration();
var later = '1 day 2 hours'.parseDateExpiration();
method
str.parseJSON([date])
Parses JSON without throwing.
str.parseJSON([date])| Parameter | Type | Description |
|---|---|---|
date? |
Boolean |
Convert JSON date strings to Date objects. Default: false |
Returns Object The parsed value or undefined.
Returns the parsed value, or undefined when the text is not valid JSON. With date set to true, strings in the JSON date format (2024-01-01T10:00:00.000Z) become Date objects.
var obj = '{"a":1}'.parseJSON(); // { a: 1 }
var bad = '{a:1'.parseJSON(); // undefined
var doc = '{"created":"2024-01-01T10:00:00.000Z"}'.parseJSON(true);
doc.created instanceof Date; // true
method
str.parseCSV([delimiter])
Parses CSV text into an array of objects with column keys a, b, c, ...
str.parseCSV([delimiter])| Parameter | Type | Description |
|---|---|---|
delimiter? |
String |
The column delimiter, one character. Default: ',' |
Returns Array An array of objects.
Each line becomes an object. The keys are column letters: a for the first column, b for the second, ..., z, then aa, ab and so on. Values in double quotes may contain the delimiter and new lines; "" inside quotes is an escaped quote. Empty columns have no key in the object. Values are strings and are not trimmed. A header line is returned like any other line.
var rows = 'name,age\n"Sirka, Peter",40\nAnna,'.parseCSV();
// [{ a: 'name', b: 'age' }, { a: 'Sirka, Peter', b: '40' }, { a: 'Anna' }]
var header = rows.shift();
for (var row of rows)
console.log(row.a, row.b || '-');
method
str.parseContext()
since 0.0.17
Parses a text made of blocks with a header and a body.
str.parseContext()Returns Array An array of objects, one per block.
Each block starts with a line of at least 20 dashes, followed by header lines key: value, another line of at least 20 dashes and the body. The body ends where the next block starts. Every block becomes an object with the header keys (lowercased, values trimmed) and a body property with the trimmed body. Header lines without : are ignored.
var text = [
'--------------------',
'Name: Hello',
'Type: note',
'--------------------',
'Body one',
'--------------------',
'Name: Second',
'--------------------',
'Body two'
].join('\n');
text.parseContext();
// [{ name: 'Hello', type: 'note', body: 'Body one' }, { name: 'Second', body: 'Body two' }]
method
str.parseEncoded()
Parses URL-encoded text (a query string or a form body) into an object.
str.parseEncoded()Returns Object The parsed keys and values (strings).
Pairs key=value are separated by &; keys and values are URL-decoded. This is the parser that Total.js uses for query strings and application/x-www-form-urlencoded bodies.
'q=total.js&page=2&name=%20Peter'.parseEncoded();
// { q: 'total.js', page: '2', name: ' Peter' }
method
str.parseConfig([def], [onerr])
Parses text in the Total.js configuration format into an object.
str.parseConfig([def], [onerr])| Parameter | Type | Description |
|---|---|---|
def? |
Object |
Default values copied into the result first. |
onerr? |
Function |
function(err, line) for values that cannot be evaluated. |
Returns Object The parsed values.
Each line is key : value. The separator is the first :, or the first = when the line has no :; the value starts at the second character after the separator, so keep one space there. Empty lines and lines that start with # or // are skipped. A value that starts with base64 or hex is decoded.
A type in brackets after the key converts the value: (string), (number) (also float, double, currency), (boolean) / (bool) (true when the value contains true, on, 1 or enabled, in any case), (json), (object) / (array) / (eval) (evaluated as JavaScript), (date), (env) (reads process.env[value]), (config) (reads another configuration key) and (random) (a random string of the given length). When an evaluated value fails, onerr(err, line) is called, or an error is thrown without it.
var text = 'name : Shop\ncount (number) : 10\nenabled (boolean) : true\n# comment\ntags (array) : [\'a\', \'b\']';
text.parseConfig();
// { name: 'Shop', count: 10, enabled: true, tags: ['a', 'b'] }
method
str.parseEnv()
Parses text in the .env format into an object.
str.parseEnv()Returns Object The keys and values.
Each line is KEY=value. Lines that are empty or start with # or // are skipped. A value in single or double quotes is unquoted (its inner spaces are kept); other values are trimmed. \n in a value becomes a new line. All values are strings.
'PORT=8000\nNAME="My app"\n# comment'.parseEnv();
// { PORT: '8000', NAME: 'My app' }
method
str.parseUA([structured])
Reads the operating system, browser and device type from a User-Agent header.
str.parseUA([structured])| Parameter | Type | Description |
|---|---|---|
structured? |
Boolean |
Return an object instead of text. Default: false |
Returns String|Object
Without arguments the result is a short text such as Windows Chrome. With structured set to true the result is an object { os, browser, device }, where device is mobile or desktop. Empty text returns an empty string.
var ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Version/17.0 Mobile Safari/604.1';
ua.parseUA(); // iPhone Safari
ua.parseUA(true); // { os: 'iPhone', browser: 'Safari', device: 'mobile' }
method
str.isEmail()
Checks that the text is an e-mail address.
str.isEmail()Returns Boolean
The test uses the email regular expression of DEF.validators: letters, digits and -_.+ before @, a domain and a top-level domain of at least two letters. Text of four characters or less is never valid.
'info@example.com'.isEmail(); // true
'info@example'.isEmail(); // false
method
str.isPhone()
Checks that the text is a phone number.
str.isPhone()Returns Boolean
The test uses the phone regular expression of DEF.validators: an optional +, three digits (optionally in brackets), three digits and 4 to 8 digits, each group optionally separated by -, . or a space. Text shorter than six characters is never valid.
'+421903123456'.isPhone(); // true
'(123) 456-7890'.isPhone(); // true
'12345'.isPhone(); // false
method
str.isURL()
Checks that the text is an http or https URL.
str.isURL()Returns Boolean
The text must start with http:// or https:// and must not contain ,, {, } or \. Text of seven characters or less is never valid.
'https://www.totaljs.com'.isURL(); // true
'www.totaljs.com'.isURL(); // false
method
str.isUID()
Checks that the text is a valid identifier made by UID().
str.isUID()Returns Boolean
The method checks the format and the checksum of identifiers created by UID(), so a random string of the same shape is rejected. To read the date and index stored in a UID use str.parseUID(), which returns { version, date, century, hash, index, valid }. For standard GUIDs (8-4-4-4-12 hex digits) use str.isGUID().
var id = UID();
id.isUID(); // true
'abc'.isUID(); // false
id.parseUID().date; // the time the id was created
'123e4567-e89b-12d3-a456-426614174000'.isGUID(); // true
method
str.isNumber([isDecimal])
Checks that the text contains only digits.
str.isNumber([isDecimal])| Parameter | Type | Description |
|---|---|---|
isDecimal? |
Boolean |
Allow one decimal separator. Default: false |
Returns Boolean
Every character must be a digit. With isDecimal set to true, one . or , is allowed as well. A sign (-, +) is not allowed and empty text is not a number.
'0123'.isNumber(); // true
'1.5'.isNumber(); // false
'1,5'.isNumber(true); // true
method
str.isJSON()
Quickly checks that the text looks like a JSON object, array or string.
str.isJSON()Returns Boolean
Leading and trailing white space is skipped and the first and last characters are compared: { with }, [ with ] or " with ". It is also true when the text starts with a digit or a letter and ends with a character below 9, for example '123' or 'abc1'. The content is not parsed, so use String.parseJSON() when you need to be sure.
var body = ' {"a":1} ';
if (body.isJSON())
var obj = body.parseJSON();
method
str.isXSS()
Checks that the text contains an HTML tag.
str.isXSS()Returns Boolean
Returns true when the text contains < followed later by >, which is how the xss regular expression of DEF.validators detects markup in user input. str.isSQLInjection() works the same way with the sqlinjection expression: it is true for quoted strings and for the SQL keywords ALTER, CREATE, DELETE, DROP, EXEC, INSERT, MERGE, SELECT, UPDATE and UNION written in uppercase. Both are simple filters, not a replacement for encoding output and for query parameters.
'<script>alert(1)</script>'.isXSS(); // true
'Hello'.isXSS(); // false
'DROP TABLE users'.isSQLInjection(); // true
method
str.hash([type], [salt])
Returns a hash of the text: a fast number hash or an md5, sha1, sha256, sha512 or crc32 digest.
str.hash([type], [salt])| Parameter | Type | Description |
|---|---|---|
type? |
String|Boolean |
md5, sha1, sha256, sha512, crc32, crc32unsigned, or true for an unsigned number hash. |
salt? |
String |
Text appended before hashing. |
Returns Number|String A number for the number hash and crc32, a hex string otherwise.
type selects the algorithm: md5, sha1, sha256, sha512 (hex strings), crc32 (signed number) or crc32unsigned (unsigned number). Without type the method returns a fast 32-bit number hash of the text (signed); hash(true) returns it unsigned. salt is appended to the text before hashing. The number hash is not a cryptographic hash: use it for cache keys and similar purposes. str.crc32([unsigned]) is also available directly.
'hello'.hash(); // a signed 32-bit number
'hello'.hash(true); // the same, unsigned
'hello'.hash('sha256'); // hex digest
'hello'.hash('crc32unsigned');
method
str.md5([salt])
Returns the MD5 digest of the text as a hex string.
str.md5([salt])| Parameter | Type | Description |
|---|---|---|
salt? |
String |
Text appended before hashing. |
Returns String 32 hex characters.
The text (with salt appended) is hashed as UTF-8 with Node.js crypto. MD5 is suitable for checksums and cache keys, not for passwords.
'a'.md5();
// 0cc175b9c0f1b6a831c399e269772661
method
str.sha256([salt])
Returns the SHA-256 digest of the text as a hex string. sha1() and sha512() work the same.
str.sha256([salt])| Parameter | Type | Description |
|---|---|---|
salt? |
String |
Text appended before hashing. |
Returns String 64 hex characters.
The text (with salt appended) is hashed as UTF-8 with Node.js crypto. str.sha1([salt]) returns 40 hex characters and str.sha512([salt]) 128 hex characters.
var digest = 'password'.sha256(CONF.secret);
var short = 'text'.sha1();
var long = 'text'.sha512();
method
str.sign([key], [check])
Signs the text with a short checksum, or checks and removes the signature.
str.sign([key], [check])| Parameter | Type | Description |
|---|---|---|
key? |
String |
The signing key. |
check? |
Boolean |
Check the signature and return the original text. Default: false |
Returns String The signed text, the original text, or null.
str.sign(key) returns text-checksum, where the checksum is made from the text and key. signed.sign(key, true) checks the checksum and returns the original text, or null when the signature does not match. Use it for values that travel through URLs and must not be changed, such as ids in links. It is not encryption: the text stays readable.
str.makeid() returns only a short base-36 checksum of the text, handy as a compact key.
var token = '123'.sign('mykey'); // 123-155hlxd
token.sign('mykey', true); // 123
(token + 'x').sign('mykey', true); // null
method
str.encrypt(key, [isUnique], [secret])
Encrypts the text with a key. String.decrypt() reverses it.
str.encrypt(key, [isUnique], [secret])| Parameter | Type | Description |
|---|---|---|
key |
String |
The encryption key. |
isUnique? |
Boolean |
Make a different result for each call. Default: false |
secret? |
String |
The secret used in the checksum. Default: CONF.secret |
Returns String The encrypted text.
The result is a string of a checksum, - and hex data. With isUnique set to true, the same text gives a different result each time. The checksum uses secret, or the secret configuration key when you omit it.
str.decrypt(key, [secret]) returns the original text, or null when the key, the secret or the data do not match. Use the same key and secret for both.
var value = 'user@example.com'.encrypt('mykey', true);
value.decrypt('mykey'); // user@example.com
value.decrypt('other'); // null
method
str.encrypt_uid([key])
Encrypts an identifier into a short URL-safe token. String.decrypt_uid() reverses it.
str.encrypt_uid([key])| Parameter | Type | Description |
|---|---|---|
key? |
String |
The key. Default: CONF.secret |
Returns String The token.
Use it to hide numeric or text ids in public URLs. key defaults to the secret configuration key. token.decrypt_uid([key]) returns the original id, or null when the token was changed or the key is different.
var token = '123'.encrypt_uid('mykey');
token.decrypt_uid('mykey'); // 123
method
str.base64ToBuffer()
Converts base64 text or a data URI to a Buffer.
str.base64ToBuffer()Returns Buffer The decoded data.
Everything up to and including the first , is skipped, so both plain base64 and data:...;base64,... work. Related methods: str.base64ToFile(filename, [callback]) writes the decoded data to a file, str.base64ContentType() returns the content type of a data URI (image/png), and str.parseDataURI() returns { type, buffer } (or null for text that is not a data URI).
var uri = 'data:text/plain;base64,aGVsbG8=';
uri.base64ToBuffer().toString(); // hello
uri.base64ContentType(); // text/plain
uri.parseDataURI().type; // text/plain
uri.base64ToFile(PATH.temp('hello.txt'));
method
num.format([decimals], [separator], [separatorDecimal])
Formats a number with a thousands separator and a fixed number of decimals.
num.format([decimals], [separator], [separatorDecimal])| Parameter | Type | Description |
|---|---|---|
decimals? |
Number |
The number of decimals. |
separator? |
String |
The thousands separator. Default: ' ' |
separatorDecimal? |
String |
The decimal separator. Default: '.' |
Returns String The formatted number.
The thousands separator is a space by default. The decimal separator is ., or , when the thousands separator is .. Extra decimals are cut, not rounded, so call Number.round() first when you need rounding. Missing decimals are filled with zeros. When the first argument is a string, the first two arguments are swapped: format('.', 2) is the same as format(2, '.').
(1234567.891).format(2); // 1 234 567.89
(1234.5).format(2, ',', '.'); // 1,234.50
(1234.5).format('.', 2); // 1.234,50
(1.999).round(2).format(2); // 2.00
method
num.pluralize(zero, one, few, other)
Picks a plural form by the number; # is replaced with the number.
num.pluralize(zero, one, few, other)| Parameter | Type | Description |
|---|---|---|
zero |
String |
Text for 0, or all four forms separated by commas. |
one? |
String |
Text for 1. |
few? |
String |
Text for 2 to 4. |
other? |
String |
Text for other numbers. |
Returns String The chosen form.
The form zero is used for 0, one for 1, few for 2 to 4 and other for the rest (the rule of Slavic languages; for English pass the same text as few and other). When you pass only one string, it is split by commas into the four forms. The first # in the chosen form is replaced with the number.
(1).pluralize('no items', '# item', '# items', '# items'); // 1 item
(7).pluralize('no items,# item,# items,# items'); // 7 items
method
num.padLeft(max, [c])
Pads the number on the left with zeros. Number.padRight() pads on the right.
num.padLeft(max, [c])| Parameter | Type | Description |
|---|---|---|
max |
Number |
The length of the result. |
c? |
String |
The padding character. Default: '0' |
Returns String The padded number.
The number is converted to a string and padded to max characters with c (0 by default). num.padRight(max, [c]) pads on the right.
(5).padLeft(3); // 005
(7).padLeft(4, ' '); // ' 7'
(5).padRight(3); // 500
method
num.round(precision)
Rounds the number to a number of decimals.
num.round(precision)| Parameter | Type | Description |
|---|---|---|
precision |
Number |
The number of decimals. |
Returns Number The rounded number.
Rounding uses exponent notation, so values like 1.005 round correctly to 1.01. num.floor(decimals) rounds down to a number of decimals instead ((1.239).floor(2) is 1.23).
(1.005).round(2); // 1.01
(2.5).round(0); // 3
(1.239).floor(2); // 1.23
method
num.fixed(decimals)
Rounds the number with toFixed() and returns a number, not a string.
num.fixed(decimals)| Parameter | Type | Description |
|---|---|---|
decimals |
Number |
The number of decimals. |
Returns Number
(1.236).fixed(2); // 1.24 (a number)
method
num.between(condition, [otherwise])
Returns the value of the first range that contains the number.
num.between(condition, [otherwise])| Parameter | Type | Description |
|---|---|---|
condition |
Object |
Ranges as keys, results as values. |
otherwise? |
Any |
The result when no range matches. |
Returns Any The value of the matching range or otherwise.
condition is an object whose keys are ranges: '1-3' (from 1 to 3, both included), '7-' (7 and more) or '-5' (5 and less). The keys are tested in order and the value of the first matching key is returned. When no range matches, otherwise is returned.
var score = 5;
score.between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }, 'unknown');
// medium
method
num.VAT(percentage, [decimals], [includedVAT])
Adds a tax to the number, or removes it from a price that includes it.
num.VAT(percentage, [decimals], [includedVAT])| Parameter | Type | Description |
|---|---|---|
percentage |
Number |
The tax rate in percent. |
decimals? |
Number |
The number of decimals. Default: 2 |
includedVAT? |
Boolean |
The number already includes the tax. Default: false |
Returns Number
Number.TAX() is the same method. Without includedVAT the result is the number increased by percentage. With includedVAT set to true the number is a price that already includes the tax, and the result is the price without the tax. The result is rounded to decimals (2 by default). You can pass the boolean as the second argument: VAT(20, true).
(100).VAT(20); // 120
(120).VAT(20, true); // 100
(99.99).TAX(10, 0); // 110
method
num.discount(percentage, [decimals])
Reduces the number by a percentage.
num.discount(percentage, [decimals])| Parameter | Type | Description |
|---|---|---|
percentage |
Number |
The discount in percent. |
decimals? |
Number |
The number of decimals. Default: 2 |
Returns Number
The result is rounded down to decimals (2 by default).
(100).discount(15); // 85
(19.99).discount(10); // 17.99
method
num.filesize([decimals], [type])
Formats a number of bytes as a human-readable size.
num.filesize([decimals], [type])| Parameter | Type | Description |
|---|---|---|
decimals? |
Number |
The number of decimals. |
type? |
String |
bytes, KB, MB, GB or TB. |
Returns String The size with its unit.
Without type the largest fitting unit is chosen: bytes, KB, MB, GB or TB (1 KB is 1024 bytes). With type the value is converted to that unit. Without decimals the value has up to two decimals and .00 is removed; with decimals it is formatted with Number.format(decimals). The arguments can be passed in either order.
(500).filesize(); // 500 bytes
(1536000).filesize(); // 1.46 MB
(5000000).filesize(1, 'MB'); // 4.7 MB
method
num.currency([currency], [a], [b], [c])
Formats the number as an amount with a currency formatter registered in DEF.currencies.
num.currency([currency], [a], [b], [c])| Parameter | Type | Description |
|---|---|---|
currency? |
String |
The key in DEF.currencies. Default: 'default' |
a, b, c? |
Any |
Extra arguments for the formatter. |
Returns String The formatted amount.
The formatter is the function DEF.currencies[currency] (or DEF.currencies.default without currency). It receives the number and the arguments a, b and c and returns the text. When no formatter exists for the currency, the result is num.format(2). Register formatters at startup, for example in a definition file.
// /definitions/currencies.js
DEF.currencies.eur = function(val) {
return val.format(2, ' ', ',') + ' €';
};
(1234.5).currency('eur'); // 1 234,50 €
(10).currency('usd'); // 10.00 (no formatter)
method
date.add(type, [value])
Returns a new date shifted by an amount of time.
date.add(type, [value])| Parameter | Type | Description |
|---|---|---|
type |
String|Number |
The unit, a string with value and unit, or milliseconds. |
value? |
Number |
The amount, negative for the past. |
Returns Date A new date.
The original date is not changed. Pass the unit and the value (add('minutes', 30)), one string with both (add('30 minutes'), add('-2 hours')) or a number of milliseconds (add(5000)).
Units: s, ss, sec, second, seconds; m, mm, min, minute, minutes; h, hh, hour, hours; d, dd, day, days; w, ww, week, weeks; M, MM, month, months; y, yyyy, year, years. The units work on the UTC parts of the date. Adding months to the end of a month follows JavaScript: 31 January plus one month is 2 March in a leap year and 3 March otherwise.
var now = new Date();
now.add('1 day');
now.add('minutes', 30);
now.add('-2 hours');
now.add(5000); // + 5 seconds
method
date.diff([date], type)
Returns the difference between two dates in seconds, minutes, hours or days.
date.diff([date], type)| Parameter | Type | Description |
|---|---|---|
date? |
Date|String|Number |
The date to compare with. Default: now |
type |
String |
The unit of the result. |
Returns Number The difference in the unit.
The result is this - date in the given unit, rounded up, so it is positive when this is later. date can be a Date, a string that Date.parse() understands or a number of milliseconds. With one argument the date is compared with the current time. Units: s / ss / second / seconds, m / mm / minute / minutes, h / hh / hour / hours, d / dd / day / days. An unknown unit returns NaN.
var created = new Date('2024-01-30T00:00:00Z');
var end = new Date('2024-01-31T10:00:00Z');
end.diff(created, 'hours'); // 34
end.diff('2024-01-01T00:00:00Z', 'days'); // 31
created.diff('seconds'); // negative: created is in the past
method
date.format([format], [resource])
Formats the date by a pattern; without a pattern returns an ISO string in UTC.
date.format([format], [resource])| Parameter | Type | Description |
|---|---|---|
format? |
String |
The pattern. |
resource? |
String |
The resource used for month and day names. |
Returns String The formatted date.
Without format the result is yyyy-MM-ddTHH:mm:ss.SSSZ in UTC. With format the parts are written in the server time zone (UTC unless the $timezone configuration key says otherwise):
yyyy,yyyear;MM,Mmonth number;MMMMmonth name,MMMits first three letters,dd,dday;ddddday name,dddits first two letters in uppercase,HH,Hhours (0-23);mm,mminutes;ss,sseconds,ww,wISO week number;aAMorPM.
Uppercase YYYY, YY, DD, D, DDDD, DDD and lowercase hh, h are accepted too. Month and day names are English; with resource they are translated with the resource file of that name. Compiled formats are cached, so formatting is fast.
var d = new Date('2024-01-31T10:00:00Z');
d.format(); // 2024-01-31T10:00:00.000Z
d.format('yyyy-MM-dd HH:mm'); // 2024-01-31 10:00
d.format('dd.MM.yy'); // 31.01.24
d.format('dddd, d. MMMM yyyy'); // Wednesday, 31. January 2024
d.format('MMMM', 'sk'); // the month name from sk.resource
method
date.extend(text)
Returns a new date with the date or time parts replaced from a text.
date.extend(text)| Parameter | Type | Description |
|---|---|---|
text |
String |
A date, a time, or both. |
Returns Date A new date.
The text can contain a date yyyy-MM-dd or d.M.yyyy and a time HH:mm or HH:mm:ss. Only the parts found in the text are replaced; the others are taken from the original date. The year, month and day are set one after another, so when the day of the original date does not exist in the new month the date moves to the next month (31 January extended with 2025-02-10 gives 10 March 2025). The values are UTC.
var d = new Date('2024-01-31T10:00:00Z');
d.extend('12:30'); // 2024-01-31T12:30:00.000Z
d.extend('2025-03-04'); // 2025-03-04T10:00:00.000Z
d.extend('1.3.2020 08:00'); // 2020-03-01T08:00:00.000Z
method
date.toUTC([ticks])
Shifts a local date by the time zone offset to UTC.
date.toUTC([ticks])| Parameter | Type | Description |
|---|---|---|
ticks? |
Boolean |
Return milliseconds. Default: false |
Returns Date|Number
The result is the date plus the offset of the server time zone. With ticks set to true the result is the number of milliseconds instead of a Date. On a server running in UTC (the default) the date does not change.
var utc = new Date().toUTC();
var ms = new Date().toUTC(true);
method
date.setTimeZone(timezone)
Returns a new date that shows the same moment in another time zone.
date.setTimeZone(timezone)| Parameter | Type | Description |
|---|---|---|
timezone |
String |
An IANA time zone name. |
Returns Date A new date.
The parts of the result (hours, day, ...) read in the server time zone are the wall-clock time of timezone at that moment, so format() prints the local time of that zone. timezone is an IANA name such as Europe/Bratislava or America/New_York.
var d = new Date('2024-01-31T10:00:00Z');
d.setTimeZone('Europe/Bratislava').format('HH:mm'); // 11:00
method
arr.findItem(cb, [value])
Returns the first item that matches, or null.
arr.findItem(cb, [value])| Parameter | Type | Description |
|---|---|---|
cb |
Function|String|Any |
A test function, a property name or a value. |
value? |
Any |
The value of the property. |
Returns Object The item or null.
Pass a function (item, index), a property name and a value (('id', 5) compares item.id === 5), or a single value that is compared with ===.
var users = [{ id: 1, name: 'Peter' }, { id: 2, name: 'Anna' }];
users.findItem('id', 2); // { id: 2, name: 'Anna' }
users.findItem(u => u.name === 'Peter'); // { id: 1, name: 'Peter' }
users.findItem('id', 9); // null
method
arr.findAll(cb, [value])
Returns all items that match.
arr.findAll(cb, [value])| Parameter | Type | Description |
|---|---|---|
cb |
Function|String|Any |
A test function, a property name or a value. |
value? |
Any |
The value of the property. |
Returns Array The matching items.
Pass a function (item, index), a property name and a value (('id', 5) compares item.id === 5), or a single value that is compared with ===. The result is a new array; the original array is not changed.
var items = [{ type: 'a' }, { type: 'b' }, { type: 'a' }];
items.findAll('type', 'a').length; // 2
method
arr.findIndex(cb, [value])
Returns the index of the first item that matches, or -1.
arr.findIndex(cb, [value])| Parameter | Type | Description |
|---|---|---|
cb |
Function|String|Any |
A test function, a property name or a value. |
value? |
Any |
The value of the property. |
Returns Number The index or -1.
Pass a function (item, index), a property name and a value (('id', 5) compares item.id === 5), or a single value that is compared with ===. Total.js replaces the native findIndex() with this version (with a function it behaves like the native one); arr.TfindIndex() is the same method.
var users = [{ id: 1 }, { id: 2 }];
var index = users.findIndex('id', 2); // 1
if (index !== -1)
users.splice(index, 1);
method
arr.findValue(cb, value, path, [def])
Finds an item and returns one of its properties.
arr.findValue(cb, value, path, [def])| Parameter | Type | Description |
|---|---|---|
cb |
Function|String |
A test function or a property name. |
value |
Any |
The value of the property (pass undefined with a function). |
path |
String |
The property to return. |
def? |
Any |
The default value. |
Returns Any
The item is found like in Array.findItem(). The result is item[path], or def when no item matches or the property is null / undefined.
var users = [{ id: 1, name: 'Peter' }];
users.findValue('id', 1, 'name'); // Peter
users.findValue('id', 9, 'name', 'guest'); // guest
method
arr.remove(cb, [value])
Returns a new array without the items that match.
arr.remove(cb, [value])| Parameter | Type | Description |
|---|---|---|
cb |
Function|String|Any |
A test function, a property name or a value. |
value? |
Any |
The value of the property. |
Returns Array A new array without the matching items.
Pass a function (item, index), a property name and a value (('id', 5) compares item.id === 5), or a single value that is compared with ===. The original array is not changed, so assign the result.
var users = [{ id: 1 }, { id: 2 }, { id: 3 }];
users = users.remove('id', 1); // [{ id: 2 }, { id: 3 }]
var nums = [1, 2, 3, 2].remove(2); // [1, 3]
method
arr.quicksort([sort], [desc])
Sorts the array in place by one or more properties.
arr.quicksort([sort], [desc])| Parameter | Type | Description |
|---|---|---|
sort? |
String|Boolean |
Properties to sort by, or true for descending plain values. |
desc? |
Boolean |
Descending order for sort. Default: false |
Returns Array The same array, sorted.
sort is a comma-separated list of property names, each optionally with _asc or _desc ('name', 'price_desc', 'group,date_desc'). Nested properties with dots are supported ('user.name'). The type of each column (string, number, boolean or Date) is detected from the first value that is not null the first time a sort expression is used, and is kept for later sorts with the same expression; strings are compared with diacritics in mind. Passing true (or 2) as the second argument sorts a single property in descending order.
Without sort the array of plain values is sorted ascending; quicksort(true) sorts it descending. The method returns the same array.
var products = [{ name: 'B', price: 10 }, { name: 'A', price: 20 }];
products.quicksort('name'); // A, B
products.quicksort('price_desc'); // 20, 10
products.quicksort('name', true); // B, A
[3, 1, 2].quicksort(); // [1, 2, 3]
method
arr.take(count)
Returns the first count items as a new array.
arr.take(count)| Parameter | Type | Description |
|---|---|---|
count |
Number |
The number of items. |
Returns Array
[1, 2, 3, 4].take(2); // [1, 2]
method
arr.skip(count)
Returns the items after the first count items as a new array.
arr.skip(count)| Parameter | Type | Description |
|---|---|---|
count |
Number |
The number of items to skip. |
Returns Array
Combine with take() for paging.
var page = 2;
var limit = 10;
var items = all.skip((page - 1) * limit).take(limit);
method
arr.first([def])
Returns the first item, or a default for an empty array. Array.last() returns the last one.
arr.first([def])| Parameter | Type | Description |
|---|---|---|
def? |
Any |
The value for an empty array. |
Returns Any
arr.last([def]) returns the last item or def.
[1, 2].first(); // 1
[].first('none'); // none
[1, 2].last(); // 2
method
arr.group(name)
Groups the items by a property.
arr.group(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The property to group by. |
Returns Array Groups { name, items }.
Returns an array of { name, items } sorted by name. The value of the property is converted to a string; items without the property are in a group with an empty name.
var items = [{ type: 'x', id: 1 }, { type: 'y', id: 2 }, { type: 'x', id: 3 }];
items.group('type');
// [{ name: 'x', items: [...2 items] }, { name: 'y', items: [...1 item] }]
method
arr.trim()
Trims strings and returns a new array without empty values.
arr.trim()Returns Array
Strings in the original array are trimmed in place. The result contains only truthy items, so empty strings, null, undefined, 0 and false are left out.
' a , ,b'.split(',').trim(); // ['a', 'b']
method
arr.random([item])
Shuffles the array in place, or returns one random item.
arr.random([item])| Parameter | Type | Description |
|---|---|---|
item? |
Boolean |
Return one random item. Default: false |
Returns Array|Any
Without arguments the array is shuffled (Fisher-Yates) and returned. With item set to true one random item is returned and the array is not changed.
var colors = ['red', 'green', 'blue'];
colors.random(true); // one color
colors.random(); // the shuffled array
method
arr.wait(onItem, [callback], [thread])
Processes the items one by one with an asynchronous function.
arr.wait(onItem, [callback], [thread])| Parameter | Type | Description |
|---|---|---|
onItem |
Function |
function(item, next). |
callback? |
Function |
Called when all items are processed. |
thread? |
Number|Boolean |
Parallel items, or true to remove items as they are processed. Default: 1 |
Returns Array The array.
onItem(item, next) is called for each item; call next() to continue with the next item. callback() is called when all items are done. thread sets how many items run at the same time (1 by default). With thread set to true the items are removed from the array with shift() as they are processed. Call next('cancel') to stop: callback('cancel') is then called.
var ids = [1, 2, 3];
ids.wait(function(id, next) {
FUNC.removeuser(id, next);
}, function() {
console.log('All removed');
});
urls.wait(function(url, next) {
REQUEST({ url: url, callback: () => next() });
}, () => console.log('done'), 2);
method
arr.async([thread], [callback])
Runs an array of functions one after another.
arr.async([thread], [callback])| Parameter | Type | Description |
|---|---|---|
thread? |
Number |
How many functions run at the same time. Default: 1 |
callback? |
Function |
Called at the end. |
Returns Array The array.
Each item is a function (next); call next() when it finishes. The functions are removed from the array as they run, so the array is empty at the end. thread sets how many functions start at the same time (1 by default). callback() is called when all functions are done, or callback('cancel') when one calls next('cancel').
var tasks = [];
tasks.push(function(next) {
console.log('first');
next();
});
tasks.push(function(next) {
setTimeout(next, 100);
});
tasks.async(function() {
console.log('done');
});
method
arr.limit(max, fn, [callback])
Processes the array in chunks of max items.
arr.limit(max, fn, [callback])| Parameter | Type | Description |
|---|---|---|
max |
Number |
The size of a chunk. |
fn |
Function |
function(items, next, beg, end). |
callback? |
Function |
Called at the end. |
Returns Array The array.
fn(items, next, beg, end) receives the next chunk and the start and end index; call next() to continue. callback() is called after the last chunk.
rows.limit(100, function(items, next) {
FUNC.importrows(items, next);
}, function() {
console.log('Imported');
});