Prototypes
Methods of String, Number, Date and Array added by Total.js 4.
On this page
Methods that Total.js 4 adds to String, Number, Date and Array. The guide Prototypes explains how to use them with examples; this page is the exact reference.
API
method
String.format([arg0], [arg1], [...])
Replaces indexed placeholders {0}, {1}... with the arguments.
String.format([arg0], [arg1], [...])| Parameter | Type | Description |
|---|---|---|
arg0? |
Object |
The value for {0}. Any number of arguments can follow. |
Returns String The formatted string.
Each {n} is replaced with the argument at index n. A null or undefined argument gives an empty string. For named placeholders use String.args().
var text = 'Hello {0}, you have {1} new messages.'.format('Peter', 5);
// Hello Peter, you have 5 new messages.
method
String.args(obj, [encode], [def])
Replaces named placeholders {key} or {{key}} with values of an object.
String.args(obj, [encode], [def])| Parameter | Type | Description |
|---|---|---|
obj |
Object |
The values. |
encode? |
Boolean|String|Function |
true (URL encoding), 'html', 'json' or a function function(value, key). |
def? |
String |
The text for a missing value. It is ignored when encode is a string. |
Returns String The string with the values.
Keys may contain letters, numbers, _, $, . and -. A missing value keeps the placeholder, or uses def when you set it.
The encode argument changes how values are written: true encodes them with encodeURIComponent(), 'html' encodes HTML entities, 'json' writes JSON.stringify(value), and a function function(value, key) returns the text itself. String.arg() is an alias.
var model = { name: 'Peter', city: 'Bratislava' };
var text = 'Hello {name} from {{city}}'.args(model);
// Hello Peter from Bratislava
var html = '<b>{name}</b>'.args({ name: '<Peter>' }, 'html');
// <b><Peter></b>
'{name} ({age})'.args({ name: 'Peter' }, null, '-');
// Peter (-)
method
String.slug([max])
Creates a URL-friendly slug from the text.
String.slug([max])| Parameter | Type | Description |
|---|---|---|
max? |
Number |
The maximum length. Default: 60 |
Returns String The slug.
The text is trimmed, lower-cased and converted to ASCII (diacritics removed). Spaces and punctuation become a single -; a trailing - is removed. The result is cut at max characters.
When the text has no usable Latin characters (for example Chinese or Cyrillic), the method returns a short hash built from the text instead.
var slug = 'Hello World: Total.js 4'.slug();
// hello-world-total-js-4
method
String.max(length, [chars])
Cuts the text to a maximum length and adds an ellipsis.
String.max(length, [chars])| Parameter | Type | Description |
|---|---|---|
length |
Number |
The maximum length of the result. |
chars? |
String |
The text appended to a cut string. Default: '...' |
Returns String The shortened text.
When the text is longer than length, it is cut so that the result with chars has exactly length characters. A shorter text is returned unchanged.
'A long description'.max(10);
// A long ...
method
String.capitalize([first])
Upper-cases the first letter of every word.
String.capitalize([first])| Parameter | Type | Description |
|---|---|---|
first? |
Boolean |
Capitalize only the first letter. Default: false |
Returns String The capitalized text.
The text is lower-cased and each letter after a space, tab or new line is upper-cased. With first set to true, only the first letter of the whole text is upper-cased.
'hello WORLD'.capitalize(); // Hello World
'hello WORLD'.capitalize(true); // Hello world
method
String.parseInt([def])
Converts the whole string to a number.
String.parseInt([def])| Parameter | Type | Description |
|---|---|---|
def? |
Number |
The value returned when the string is not a number. Default: 0 |
Returns Number The number, or def.
The string is trimmed and converted with the unary + operator, so the whole string must be a number: '12px' is not a number and gives def. To read a number from a longer text, use String.parseInt2().
var page = (this.query.page || '').parseInt(1);
'42'.parseInt(); // 42
'abc'.parseInt(-1); // -1
method
String.parseInt2([def])
Reads the first integer found in the text.
String.parseInt2([def])| Parameter | Type | Description |
|---|---|---|
def? |
Number |
The value returned when the text contains no number. Default: 0 |
Returns Number The number, or def.
Unlike String.parseInt(), the number may be surrounded by other text. A leading - is kept. String.parseFloat2() works the same way for decimal numbers (a , decimal separator is accepted).
'Width: 120px'.parseInt2(); // 120
'Price: 12,50 EUR'.parseFloat2(); // 12.5
method
String.parseFloat([def])
Converts the string to a decimal number.
String.parseFloat([def])| Parameter | Type | Description |
|---|---|---|
def? |
Number |
The value returned when the string is not a number. Default: 0 |
Returns Number The number, or def.
The string is trimmed and a , decimal separator is replaced with .. The whole string must be a number, otherwise def is returned.
'12,5'.parseFloat(); // 12.5
'x'.parseFloat(0.1); // 0.1
method
String.parseBoolean()
Converts true, 1 or on to true.
String.parseBoolean()Returns Boolean
The comparison ignores case. Every other value gives false.
var enabled = (this.body.enabled || '').parseBoolean();
'ON'.parseBoolean(); // true
method
String.parseDate([format])
Converts the string to a Date.
String.parseDate([format])| Parameter | Type | Description |
|---|---|---|
format? |
String |
The format of the input, for example 'dd/MM/yyyy'. |
Returns Date The parsed date.
Without format, the method reads ISO strings (2024-01-15T10:30:00.000Z), yyyy-MM-dd HH:mm:ss, dd.MM.yyyy HH:mm and any value that new Date() understands. A missing date part uses today.
With format, the digits of the string are read in the order of the format letters (yyyy, MM, dd, HH, mm, ss). A pm in the text adds 12 hours.
var a = '2024-01-15 10:30'.parseDate();
var b = '15/01/2024'.parseDate('dd/MM/yyyy');
method
String.parseJSON([date])
Parses JSON without throwing an exception.
String.parseJSON([date])| Parameter | Type | Description |
|---|---|---|
date? |
Boolean |
Convert ISO date strings to dates. Default: false |
Returns Object The parsed value, or undefined for invalid JSON.
Invalid JSON returns undefined instead of an error. With date set to true, ISO date strings are converted to Date objects.
var obj = '{"name":"Peter","created":"2024-01-15T10:30:00.000Z"}'.parseJSON(true);
// obj.created instanceof Date === true
var bad = '{name'.parseJSON(); // undefined
method
String.parseENV()
Parses KEY=value lines (the .env format) into an object.
String.parseENV()Returns Object The keys and their string values.
Empty lines and lines starting with # or // are skipped. Values in double or single quotes lose the quotes, and \n becomes a new line. Unquoted values are trimmed.
require('fs').readFile(PATH.root('.env'), 'utf8', function(err, text) {
if (!err) {
var env = text.parseENV();
console.log(env.DATABASE);
}
});
method
String.isEmail()
Checks whether the string is an email address.
String.isEmail()Returns Boolean
The test uses the DEF.validators.email regular expression, so you can replace it. Strings of 4 characters or less are always false.
if (!this.body.email.isEmail()) {
this.invalid('Invalid email');
return;
}
method
String.isPhone()
Checks whether the string is a phone number.
String.isPhone()Returns Boolean
The test uses the DEF.validators.phone regular expression. Strings shorter than 6 characters are always false.
'+421903123456'.isPhone(); // true
method
String.isURL()
Checks whether the string is a URL address.
String.isURL()Returns Boolean
The test uses the DEF.validators.url regular expression. Strings of 7 characters or less are always false.
'https://www.totaljs.com'.isURL(); // true
method
String.isUID()
Checks whether the string is a valid identifier created by UID().
String.isUID()Returns Boolean
The method tests the format with DEF.validators.uid and then the checksum that UID() writes into every identifier, so a random string with the right characters is not accepted.
function detail(id) {
if (!id.isUID()) {
this.throw404();
return;
}
// ...
}
method
String.isJSON()
Checks whether the string looks like JSON.
String.isJSON()Returns Boolean
Only the first and last non-white characters are tested: {...}, [...], "..." or a number. The content is not parsed; use String.parseJSON() for that.
'{"a":1}'.isJSON(); // true
'hello'.isJSON(); // false
method
String.hash([type], [salt])
Creates a hash of the string.
String.hash([type], [salt])| Parameter | Type | Description |
|---|---|---|
type? |
String|Boolean |
The algorithm, or true for an unsigned number hash. |
salt? |
String |
Text appended before hashing. |
Returns String|Number A hex string for md5/sha*, otherwise a number.
The type selects the algorithm: 'md5', 'sha1', 'sha256', 'sha512' (hex strings), 'crc32' or 'crc32unsigned' (numbers). Without a type, the method returns a fast 32-bit number hash; true makes it unsigned. The salt is appended to the string before hashing.
'hello'.hash(); // a 32-bit number
'hello'.hash(true); // an unsigned 32-bit number
'hello'.hash('sha256'); // a hex string
'hello'.hash('crc32unsigned');
method
String.md5([salt])
Returns the MD5 hash as a hex string.
String.md5([salt])| Parameter | Type | Description |
|---|---|---|
salt? |
String |
Text appended before hashing. |
Returns String A 32-character hex string.
The salt is appended to the string before hashing. Use it for checksums and cache keys, not for passwords.
var key = JSON.stringify(this.query).md5();
method
String.sha256([salt])
Returns the SHA-256 hash as a hex string.
String.sha256([salt])| Parameter | Type | Description |
|---|---|---|
salt? |
String |
Text appended before hashing. |
Returns String A 64-character hex string.
The salt is appended to the string before hashing. String.sha1([salt]) and String.sha512([salt]) work the same way with the other algorithms.
var hash = model.password.sha256(CONF.secret);
var short = 'hello'.sha1();
var long = 'hello'.sha512();
method
String.encode()
Encodes HTML special characters.
String.encode()Returns String The encoded text.
Replaces <, >, ", ' and & with HTML entities, so the text can be written safely into HTML.
'<script>alert("x")</script>'.encode();
// <script>alert("x")</script>
method
String.decode()
Decodes HTML entities back to characters.
String.decode()Returns String The decoded text.
Named entities and numeric entities (A, A) are converted. It is the opposite of String.encode().
'<b>Hello</b>'.decode(); // <b>Hello</b>
method
String.encrypt(key, [isUnique], [secret])
Encrypts the string with a key.
String.encrypt(key, [isUnique], [secret])| Parameter | Type | Description |
|---|---|---|
key |
String |
The encryption key. |
isUnique? |
Boolean |
Make every result different. Default: false |
secret? |
String |
An additional secret. Default: CONF.secret |
Returns String The encrypted string.
With isUnique set to true, every call gives a different result for the same input. The result contains a checksum made from secret (default CONF.secret) and the key, which String.decrypt() checks. Use it for tokens and URLs, not for storing passwords.
var token = JSON.stringify({ id: user.id }).encrypt('my-key', true);
method
String.decrypt(key, [secret])
Decrypts a string created by String.encrypt().
String.decrypt(key, [secret])| Parameter | Type | Description |
|---|---|---|
key |
String |
The encryption key. |
secret? |
String |
The additional secret. Default: CONF.secret |
Returns String The original string, or null.
Use the same key and secret as for encryption. A wrong key, a wrong secret or a changed string returns null.
var data = (this.query.token || '').decrypt('my-key');
var obj = data ? data.parseJSON() : null;
method
String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])
Extracts keywords from the text, sorted by frequency.
String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])| Parameter | Type | Description |
|---|---|---|
forSearch? |
Boolean |
Normalize the words for search. Default: true |
alternative? |
Boolean |
Shorten every word to 80% of its length. Default: false |
max_count? |
Number |
The maximum number of words read. Default: 200 |
max_length? |
Number |
The maximum length of a word. Default: 20 |
min_length? |
Number |
The minimum length of a word. Default: 2 |
Returns String[] Unique words, the most frequent first.
With forSearch (default true) the text is converted to ASCII and y becomes i, which makes searching tolerant. With alternative, each word is shortened to 80% of its length. Words shorter than min_length or longer than max_length are skipped. String.toKeywords() is an alias.
var words = (item.name + ' ' + item.description).keywords();
item.search = words.join(' ');
method
String.toSearch()
Normalizes the text for a full-text search.
String.toSearch()Returns String The normalized text.
The text is lower-cased and converted to ASCII, special characters are removed, y becomes i and repeated letters are merged. Apply it to both the stored text and the searched phrase.
var q = (this.query.q || '').toSearch();
method
String.toASCII()
Removes diacritics from the text.
String.toASCII()Returns String The text without diacritics.
Accented letters are replaced with their basic Latin letters, for example á with a.
'Žltý kôň'.toASCII(); // Zlty kon
method
String.removeTags()
Removes HTML tags from the text.
String.removeTags()Returns String The plain text.
Only the tags are removed; the text between them stays. HTML entities are not decoded.
'<p>Hello <b>world</b></p>'.removeTags(); // Hello world
method
String.padLeft(max, [c])
Pads the string on the left to the length max.
String.padLeft(max, [c])| Parameter | Type | Description |
|---|---|---|
max |
Number |
The final length. |
c? |
String |
The padding character. Default: ' ' |
Returns String The padded string.
A string that is already max characters or longer is returned unchanged.
'7'.padLeft(3, '0'); // 007
method
String.padRight(max, [c])
Pads the string on the right to the length max.
String.padRight(max, [c])| Parameter | Type | Description |
|---|---|---|
max |
Number |
The final length. |
c? |
String |
The padding character. Default: ' ' |
Returns String The padded string.
A string that is already max characters or longer is returned unchanged.
'Name'.padRight(10) + '|'; // 'Name |'
method
String.startsWith(text, [ignoreCase])
Checks whether the string starts with text, optionally ignoring case.
String.startsWith(text, [ignoreCase])| Parameter | Type | Description |
|---|---|---|
text |
String |
The text to find. |
ignoreCase? |
Boolean|Number |
true to ignore case, or a start position. |
Returns Boolean
Total.js replaces the native method. With ignoreCase set to true the comparison ignores case; a number is used as the start position. String.endsWith(text, [ignoreCase]) works the same way at the end of the string.
'Hello World'.startsWith('hello', true); // true
'photo.JPG'.endsWith('.jpg', true); // true
method
String.markdown([opt])
since 0.0.92
Converts Markdown to HTML.
String.markdown([opt])| Parameter | Type | Description |
|---|---|---|
opt? |
Object |
The options described above. |
Returns String The HTML.
The result is wrapped in <div class="markdown markdown-container"> unless opt.wrap is false. Most features are on by default and you turn one off with false: ul, code, images, links, formatting, icons, tables, br, headlines, hr, blockquotes, sections, footnotes, urlify, keywords, emptynewline, bookmarks. Other options: linetag (the tag of a paragraph, default 'p'), prefix (a prefix for generated ids), custom (a function that changes each line) and html (a function function(html, type) that changes the generated HTML).
var html = '# Title\n\nSome **bold** text.'.markdown();
var html = text.markdown({ wrap: false, images: false });
method
String.tslash()
since 0.0.95
Removes trailing slashes.
String.tslash()Returns String The string without trailing slashes.
All / characters at the end are removed, but a single / is kept, so '/' stays '/'.
'https://www.totaljs.com/'.tslash(); // https://www.totaljs.com
'/products//'.tslash(); // /products
method
String.toJSONSchema([name], [url])
Creates a JSON schema object from an inline definition.
String.toJSONSchema([name], [url])| Parameter | Type | Description |
|---|---|---|
name? |
String |
The name of the schema used in $id. |
url? |
String |
The base URL of $id. Default: CONF.url |
Returns Object The JSON schema.
The definition is a list of name:type pairs separated by commas or new lines. A * or ! before the name makes the field required. Types: string, email, phone, url, uid, name, zip, lower, upper, capitalize, color, icon, base64, number, int, float, boolean, date, object. string(50) sets a maximum length, [string] makes an array, {draft|published} an enum, and @name uses another schema.
The $id is built from url (default CONF.url) and name.
var schema = '*name:string(50), *email:email, age:number, tags:[string], status:{draft|published}'.toJSONSchema('user');
// schema.required: ['name', 'email']
method
Number.format([decimals], [separator], [separatorDecimal])
Formats the number with a thousands separator and decimals.
Number.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 default thousands separator is a space. Decimals are cut (not rounded) or padded with zeros to decimals. The decimal separator is ., or , when the thousands separator is .. You can also pass the separator first: format(',', 2).
(1234567.891).format(2); // 1 234 567.89
(1234.5).format(2, '.'); // 1.234,50
(1234.5).format(2, ',', '.'); // 1,234.50
method
Number.pluralize(zero, one, few, other)
Chooses a word form by the number.
Number.pluralize(zero, one, few, other)| Parameter | Type | Description |
|---|---|---|
zero |
String |
The form for 0, or all forms separated by commas. |
one? |
String |
The form for 1. |
few? |
String |
The form for 2 to 4. |
other? |
String |
The form for other numbers. |
Returns String The chosen form.
zero is used for 0, one for 1, few for 2 to 4 and other for the rest. A # in the chosen form is replaced with the number. You can also pass all forms as one comma-separated string.
var count = 3;
count.pluralize('no items', '# item', '# items', '# items'); // 3 items
count.pluralize('no items,# item,# items,# items'); // 3 items
method
Number.padLeft(max, [c])
Converts the number to a string padded on the left.
Number.padLeft(max, [c])| Parameter | Type | Description |
|---|---|---|
max |
Number |
The final length. |
c? |
String |
The padding character. Default: '0' |
Returns String The padded number.
The default padding character is 0.
(42).padLeft(6); // 000042
method
Number.padRight(max, [c])
Converts the number to a string padded on the right.
Number.padRight(max, [c])| Parameter | Type | Description |
|---|---|---|
max |
Number |
The final length. |
c? |
String |
The padding character. Default: '0' |
Returns String The padded number.
The default padding character is 0.
(42).padRight(5); // 42000
method
Number.round([precision])
Rounds the number to a number of decimals.
Number.round([precision])| Parameter | Type | Description |
|---|---|---|
precision? |
Number |
The number of decimals. Default: 0 |
Returns Number The rounded number.
Without precision the number is rounded to an integer.
(3.14159).round(2); // 3.14
(2.5).round(); // 3
method
Number.floor(decimals)
Rounds the number down to a number of decimals.
Number.floor(decimals)| Parameter | Type | Description |
|---|---|---|
decimals |
Number |
The number of decimals. |
Returns Number The number rounded down.
It works like Math.floor() with decimals.
(3.14959).floor(2); // 3.14
method
Number.between(condition, otherwise)
Returns a value from a map of number ranges.
Number.between(condition, otherwise)| Parameter | Type | Description |
|---|---|---|
condition |
Object |
Ranges as keys and results as values. |
otherwise |
Object |
The value when no range matches. |
Returns Object The value of the matching range.
Keys of condition are ranges: '1-5' (from 1 to 5), '10-' (10 and more) or '-5' (5 and less). The value of the first matching range is returned, otherwise otherwise.
var label = (4).between({ '1-2': 'bad', '3-4': 'good', '5-': 'excellent' }, 'none');
// good
method
Number.add(value, [decimals])
Applies a math operation written as a string.
Number.add(value, [decimals])| Parameter | Type | Description |
|---|---|---|
value |
Number|String |
A number, or an operation such as '-5' or '+20%'. |
decimals? |
Number |
Round the result down to these decimals. |
Returns Number The result.
A number is added. A string starts with an operator +, -, * or / followed by a number, for example '+10'. With % at the end the operand is a percentage of the number: '+20%' adds 20%. With decimals the result is rounded down to that number of decimals.
(100).add('+20%'); // 120
(100).add('-5'); // 95
(100).add('*2'); // 200
method
Number.VAT(percentage, [decimals], [includedVAT])
Adds VAT to the price, or removes it.
Number.VAT(percentage, [decimals], [includedVAT])| Parameter | Type | Description |
|---|---|---|
percentage |
Number |
The VAT rate in percent. |
decimals? |
Number |
The number of decimals. Default: 2 |
includedVAT? |
Boolean |
The number already includes VAT. Default: false |
Returns Number The price.
Without includedVAT the method returns the price with VAT. With includedVAT set to true, the number is a price with VAT and the method returns the price without it. The result is rounded to decimals.
(100).VAT(20); // 120
(120).VAT(20, 2, true); // 100
method
Number.discount(percentage, [decimals])
Subtracts a percentage discount.
Number.discount(percentage, [decimals])| Parameter | Type | Description |
|---|---|---|
percentage |
Number |
The discount in percent. |
decimals? |
Number |
The number of decimals. Default: 2 |
Returns Number The discounted number.
The result is rounded down to decimals.
(80).discount(15); // 68
method
Number.filesize([decimals], [type])
Formats a number of bytes as a readable file size.
Number.filesize([decimals], [type])| Parameter | Type | Description |
|---|---|---|
decimals? |
Number |
The number of decimals. |
type? |
String |
The unit: 'bytes', 'KB', 'MB', 'GB' or 'TB'. |
Returns String The size with the unit.
Without type the unit is chosen automatically (bytes, KB, MB, GB or TB). With type the value is converted to that unit. Without decimals the value has up to 2 decimals.
(1536).filesize(); // 1.50 KB
(5242880).filesize(0, 'MB'); // 5 MB
method
Number.async(fn, [callback])
Runs an asynchronous function the number of times, counting down.
Number.async(fn, [callback])| Parameter | Type | Description |
|---|---|---|
fn |
Function |
The function function(number, next). |
callback? |
Function |
Called after the last run. |
Returns Number
The function gets the current number (from the start value down to 1) and next. The next run starts after you call next(). When the count reaches zero, callback is called.
(3).async(function(number, next) {
console.log(number); // 3, 2, 1
setTimeout(next, 100);
}, function() {
console.log('Done');
});
method
Date.add(type, [value])
Returns a new date moved by a time period.
Date.add(type, [value])| Parameter | Type | Description |
|---|---|---|
type |
String|Number |
The unit, an expression such as '5 days', or milliseconds. |
value? |
Number |
The amount. |
Returns Date A new date.
Pass a type and a value (add('days', 5)) or one expression (add('5 days')). Types: seconds, minutes, hours, days, weeks, months, years, also the short forms s, m, h, d, w, M, y. Negative values move back. A number adds milliseconds. The original date is not changed.
var expire = NOW.add('1 month');
var yesterday = NOW.add('days', -1);
var later = NOW.add('2 hours');
method
Date.format([format], [resource])
Formats the date as a string.
Date.format([format], [resource])| Parameter | Type | Description |
|---|---|---|
format? |
String |
The format, for example 'dd.MM.yyyy HH:mm'. |
resource? |
String |
The resource file with translated month and day names. |
Returns String The formatted date.
Without format the date is returned as an ISO string in UTC. Format tokens use the local time: yyyy, yy, MM, M, MMM (short month name), MMMM (month name), dd, d, ddd (short day name), dddd (day name), HH, H, mm, m, ss, s, ww (ISO week), a (AM/PM). Month and day names are English; with resource they are read from that resource file.
var dt = new Date(2024, 0, 15, 9, 5);
dt.format('yyyy-MM-dd'); // 2024-01-15
dt.format('dd.MM.yyyy HH:mm'); // 15.01.2024 09:05
dt.format('dddd, d. MMMM'); // Monday, 15. January
dt.format(); // ISO string in UTC
method
Date.diff([date], type)
Returns the difference between two dates in a unit.
Date.diff([date], type)| Parameter | Type | Description |
|---|---|---|
date? |
Date|Number|String |
The date to compare with. Default: now |
type |
String |
The unit. |
Returns Number The difference.
The difference is this - date, rounded up. Without date the method compares with now. Units: seconds, minutes, hours, days, months, years and the short forms s, m, h, d, M, y. A month counts as 28 days. An unknown unit gives NaN.
var left = item.expire.diff('days');
var age = NOW.diff(user.dtcreated, 'hours');
method
Date.toUTC([ticks])
Shifts the date by the local timezone offset.
Date.toUTC([ticks])| Parameter | Type | Description |
|---|---|---|
ticks? |
Boolean |
Return milliseconds. Default: false |
Returns Date|Number
The result shows the UTC time in the local fields of the date. With ticks set to true, the method returns milliseconds instead of a date.
var utc = new Date().toUTC();
var ticks = new Date().toUTC(true);
method
Date.extend(date)
Returns a new date with parts set from a string.
Date.extend(date)| Parameter | Type | Description |
|---|---|---|
date |
String |
The date or time parts, for example '12:00' or '2024-12-24 18:00'. |
Returns Date A new date.
The string may contain a date (yyyy-MM-dd or dd.MM.yyyy) and a time (HH:mm or HH:mm:ss). Only the given parts are changed; they are set in UTC.
var noon = NOW.extend('12:00');
var eve = NOW.extend('2024-12-24 18:00');
method
Date.setTimeZone(timezone)
Returns a new date converted to a timezone.
Date.setTimeZone(timezone)| Parameter | Type | Description |
|---|---|---|
timezone |
String |
The IANA timezone name. |
Returns Date A new date.
The timezone is an IANA name such as 'Europe/Bratislava'.
var dt = new Date().setTimeZone('America/New_York');
method
Array.findItem(cb, [value])
Returns the first matching item, or null.
Array.findItem(cb, [value])| Parameter | Type | Description |
|---|---|---|
cb |
Function|String |
A function or a property name. |
value? |
Object |
The value of the property. |
Returns Object The item, or null.
cb is a function function(item, index), or a property name compared with value (===). With a single non-function argument the items themselves are compared.
var user = users.findItem('id', id);
var admin = users.findItem(item => item.role === 'admin');
method
Array.findAll(cb, [value])
Returns all matching items.
Array.findAll(cb, [value])| Parameter | Type | Description |
|---|---|---|
cb |
Function|String |
A function function(item, index) or a property name. |
value? |
Object |
The value of the property. |
Returns Array The matching items.
The arguments are the same as in Array.findItem(). The result is a new array.
var active = users.findAll('active', true);
var adults = users.findAll(item => item.age >= 18);
method
Array.findIndex(cb, [value])
Returns the index of the first matching item, or -1.
Array.findIndex(cb, [value])| Parameter | Type | Description |
|---|---|---|
cb |
Function|String |
A function or a property name. |
value? |
Object |
The value of the property. |
Returns Number The index, or -1.
Total.js replaces the native method so it also accepts a property name and a value. A function is called as function(item, index). Array.TfindIndex() is the same method under a name that other modules do not override.
var index = users.findIndex('id', id);
if (index !== -1)
users.splice(index, 1);
method
Array.TfindIndex(cb, [value])
since 0.0.95
An alias of Array.findIndex() that other modules do not override.
Array.TfindIndex(cb, [value])| Parameter | Type | Description |
|---|---|---|
cb |
Function|String |
A function or a property name. |
value? |
Object |
The value of the property. |
Returns Number The index, or -1.
Some NPM modules replace Array.prototype.findIndex with their own version. TfindIndex() keeps the Total.js behaviour (property name and value) in that case. findItem() and findValue() use it internally.
var index = users.TfindIndex('id', id);
method
Array.findValue(cb, value, path, [def])
Finds an item and returns one of its properties.
Array.findValue(cb, value, path, [def])| Parameter | Type | Description |
|---|---|---|
cb |
Function|String |
A function or a property name. |
value |
Object |
The value of the property. |
path |
String |
The property to return. |
def? |
Object |
The default value. |
Returns Object The property value, or def.
The item is found like in Array.findItem(); then its property path is returned. When there is no item or the property is null/undefined, def is returned.
var name = users.findValue('id', id, 'name', 'Unknown');
method
Array.remove(cb, [value])
Returns a new array without the matching items.
Array.remove(cb, [value])| Parameter | Type | Description |
|---|---|---|
cb |
Function|String|Object |
A function, a property name or an item. |
value? |
Object |
The value of the property. |
Returns Array A new array.
The arguments are the same as in Array.findItem(). The original array is not changed, so assign the result.
users = users.remove('id', id);
numbers = [1, 2, 3, 2].remove(2); // [1, 3]
method
Array.take(count)
Returns the first count items.
Array.take(count)| Parameter | Type | Description |
|---|---|---|
count |
Number |
The number of items. |
Returns Array A new array.
The result is a new array.
[1, 2, 3, 4, 5].take(3); // [1, 2, 3]
method
Array.skip(count)
Returns the items after the first count items.
Array.skip(count)| Parameter | Type | Description |
|---|---|---|
count |
Number |
The number of skipped items. |
Returns Array A new array.
Together with Array.take() it makes simple paging.
var page = 2;
var limit = 10;
var items = all.skip((page - 1) * limit).take(limit);
method
Array.first([def])
Returns the first item, or def for an empty array.
Array.first([def])| Parameter | Type | Description |
|---|---|---|
def? |
Object |
The value for an empty array. |
Returns Object
var item = response.items.first(null);
method
Array.last([def])
Returns the last item, or def for an empty array.
Array.last([def])| Parameter | Type | Description |
|---|---|---|
def? |
Object |
The value for an empty array. |
Returns Object
[1, 2, 3].last(); // 3
method
Array.quicksort([sort], [desc])
Sorts the array in place.
Array.quicksort([sort], [desc])| Parameter | Type | Description |
|---|---|---|
sort? |
String|Boolean |
The properties to sort by, or true for descending primitive values. |
desc? |
Boolean |
Sort descending. Default: false |
Returns Array The same array.
sort is a property name with an optional _asc or _desc suffix, for example 'name' or 'price_desc'. Several properties are separated by commas ('name_asc,price_desc') and nested properties use dots. Strings, numbers, booleans and dates are compared by their type. With desc set to true, the order is reversed.
Without arguments, primitive values are sorted ascending; quicksort(true) sorts them descending.
products.quicksort('price_desc');
products.quicksort('category,name');
users.quicksort('dtcreated', true);
method
Array.toObject([name])
Creates an object (a lookup map) from the array.
Array.toObject([name])| Parameter | Type | Description |
|---|---|---|
name? |
String |
The property used as the key. |
Returns Object The lookup object.
With name, each item is stored under the value of its property name. Without it, each item becomes a key with the value true.
var byid = users.toObject('id');
var user = byid[id];
var allowed = ['admin', 'editor'].toObject();
// { admin: true, editor: true }
method
Array.trim()
Trims strings and removes empty items.
Array.trim()Returns Array A new array.
Strings are trimmed, and items that are empty after trimming (or are null, 0, false) are removed. It returns a new array.
'a, b, ,c'.split(',').trim(); // ['a', 'b', 'c']
method
Array.wait(onItem, [callback], [thread])
Processes items one by one with an asynchronous function.
Array.wait(onItem, [callback], [thread])| Parameter | Type | Description |
|---|---|---|
onItem |
Function |
The function function(item, next, index). |
callback? |
Function |
Called after the last item. |
thread? |
Number|Boolean |
The number of parallel items, or true to remove items. Default: 1 |
Returns Array The same array.
onItem(item, next, index) is called for each item; call next() to continue. callback is called after the last item. thread sets how many items are processed at once (default 1). With thread set to true, the items are removed from the array while they are processed. Call next('cancel') to stop; callback then gets 'cancel'.
users.wait(function(user, next) {
MAIL(user.email, 'News', '=mails/news', user, next);
}, function() {
console.log('All sent');
});
method
Array.async([thread], [callback])
Runs an array of asynchronous functions.
Array.async([thread], [callback])| Parameter | Type | Description |
|---|---|---|
thread? |
Number |
The number of parallel functions. Default: 1 |
callback? |
Function |
Called at the end. |
Returns Array The same array.
Each item is a function function(next). The items are removed from the array as they run. thread sets how many functions run at once (default 1). callback is called after the last function, or with 'cancel' when a function calls next('cancel').
var tasks = [];
tasks.push(function(next) {
// load something
next();
});
tasks.push(function(next) {
// save something
next();
});
tasks.async(function() {
console.log('Done');
});
method
Array.limit(max, fn, [callback])
Processes the array in chunks of max items.
Array.limit(max, fn, [callback])| Parameter | Type | Description |
|---|---|---|
max |
Number |
The size of a chunk. |
fn |
Function |
The function function(items, next, beg, end). |
callback? |
Function |
Called after the last chunk. |
Returns Array The same array.
fn(items, next, beg, end) gets the next chunk; call next() to continue with the following chunk. callback is called after the last chunk.
rows.limit(100, function(items, next) {
// insert 100 items at once
next();
}, function() {
console.log('Imported');
});
method
Array.random([item])
Shuffles the array, or returns a random item.
Array.random([item])| Parameter | Type | Description |
|---|---|---|
item? |
Boolean |
Return one random item. Default: false |
Returns Array|Object
Without arguments the array is shuffled in place (Fisher-Yates) and returned. With item set to true, one random item is returned and the array is not changed.
var deck = [1, 2, 3, 4, 5].random();
var winner = users.random(true);
method
String.parseCSV([delimiter])
Parses CSV text into an array of objects.
String.parseCSV([delimiter])| Parameter | Type | Description |
|---|---|---|
delimiter? |
String |
The column delimiter. Default: ',' |
Returns Object[] One object per line, with the keys a, b, c...
Every line becomes one object. The columns are named by letters: the first is a, the second b and so on. Values in double quotes may contain the delimiter and new lines, and "" inside quotes is an escaped quote. All values stay strings, and an empty column has no key in the object. A header line is not detected, so it comes back as the first object.
var csv = 'Peter,30,"Bratislava, SK"\nAnna,25,Prague';
var rows = csv.parseCSV();
// [{ a: 'Peter', b: '30', c: 'Bratislava, SK' }, { a: 'Anna', b: '25', c: 'Prague' }]
'name;age\nPeter;30'.parseCSV(';');
method
String.parseUA([structured])
Reads the operating system, browser and device type from a user agent string.
String.parseUA([structured])| Parameter | Type | Description |
|---|---|---|
structured? |
Boolean |
Return an object instead of a text. Default: false |
Returns String|Object The detected names, or { os, browser, device }.
Without an argument the method returns a short text with the detected names, such as Mac Chrome or iOS iPhone Mobile Safari. With structured set to true it returns an object { os, browser, device }, where device is desktop, mobile, tablet or tv. An empty string returns an empty string.
var ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36';
ua.parseUA(); // Mac Chrome
ua.parseUA(true); // { os: 'Mac', browser: 'Chrome', device: 'desktop' }
// in a controller
var info = (self.req.headers['user-agent'] || '').parseUA(true);
method
String.parseEncoded()
Parses application/x-www-form-urlencoded text into an object.
String.parseEncoded()Returns Object The parsed keys and values.
The text looks like a query string: key=value&key2=value2. + becomes a space and %xx sequences are decoded. All values stay strings; a repeated key joins its values with a comma. Keys may contain only letters, digits and -, _, ., [, ], and parsing stops at the first other character in a key. The number of keys is limited by CONF.default_request_maxkeys and the length of a key by CONF.default_request_maxkey.
var data = 'name=Peter+Sirka&tags=a&tags=b&city=Bratislava%2C%20SK'.parseEncoded();
// { name: 'Peter Sirka', tags: 'a,b', city: 'Bratislava, SK' }
method
String.parseXML([replace])
Parses XML into a flat object of paths and values.
String.parseXML([replace])| Parameter | Type | Description |
|---|---|---|
replace? |
Boolean |
Replace special characters in the keys with _. Default: false |
Returns Object The flat object of paths.
Every element with text becomes a key made of the element names joined with dots, for example book.title. A repeated element gives an array of values. The attributes of an element are stored as an object under the path followed by []. CDATA sections are read as text and comments are skipped. With replace set to true, the characters [, ], :, . and _ in the keys are replaced with _.
var xml = '<book id="1"><title>Total.js</title><tag>node</tag><tag>web</tag></book>';
var obj = xml.parseXML();
// obj['book.title'] === 'Total.js'
// obj['book.tag'] => ['node', 'web']
// obj['book[]'] => { id: '1' }
method
String.parseHTML([trim])
since 0.0.67
Parses HTML into a tree of elements that you can search and change.
String.parseHTML([trim])| Parameter | Type | Description |
|---|---|---|
trim? |
Boolean |
Trim the text content. Default: false |
Returns HTMLElement The root element of the parsed document.
The method uses the built-in HTML parser and returns the root element. Elements have tagName, attrs, children and parentNode, and the methods find(selector), closest(selector), parent(), attr(), aclass(), rclass(), hclass(), tclass(), css(), append(), prepend(), remove(), text() and html([formatted]). With trim set to true, the text inside the elements is trimmed.
var dom = '<div><a href="/docs/" class="link">Docs</a></div>'.parseHTML(true);
var links = dom.find('a');
for (var i = 0; i < links.length; i++)
links[i].attr('target', '_blank');
console.log(dom.html());
method
String.parseComponent(tags)
Cuts tagged blocks out of a text and returns their content by name.
String.parseComponent(tags)| Parameter | Type | Description |
|---|---|---|
tags |
Object |
The name and the opening tag of each block. |
Returns Object The content of every block that was found.
tags maps a name to an opening tag, for example { js: '<script>', css: '<style>' }. For each name the content between the opening tag and its closing tag is returned (nested tags of the same kind are counted). A missing tag gives no key. Total.js uses it to read the <script total> part of .html plugins and components.
var html = '<style>.box { color: red; }</style>\n<script>console.log(1);</script>\n<div class="box"></div>';
var parts = html.parseComponent({ css: '<style>', js: '<script>' });
// parts.css === '.box { color: red; }'
// parts.js === 'console.log(1);'
method
String.parseTerminal([fields], fn, [skip], [take])
Parses the column output of a terminal command line by line.
String.parseTerminal([fields], fn, [skip], [take])| Parameter | Type | Description |
|---|---|---|
fields? |
Array |
Header names or regular expressions of the columns. |
fn |
Function |
Called as fn(values, index, count, line) for every line. |
skip? |
Number |
The number of lines to skip. Default: 0 |
take? |
Number |
The number of lines to read. Default: all |
Returns String The same string.
With fields, the first non-empty line (of the first three) is the header. Each field is a header name (String) or a RegExp that finds the column in the header line, and fn gets the values of those columns for every following line. Without fields, every line is split into words and fn gets the array of words. fn(values, index, count, line) gets the values, the index of the parsed line, the end index and the line number. skip and take limit the lines. The method returns the string itself.
var Exec = require('child_process').exec;
Exec('df -h', function(err, output) {
output.parseTerminal(['Filesystem', 'Size', 'Used'], function(values) {
console.log(values[0], values[1], values[2]);
});
});
method
String.parseConfig([def], [onerror])
Parses text in the Total.js config format into an object.
String.parseConfig([def], [onerror])| Parameter | Type | Description |
|---|---|---|
def? |
Object |
Default values copied into the result. |
onerror? |
Function |
Called as onerror(err, line) when an object or eval value fails. |
Returns Object The parsed values.
Each line is key : value, and lines starting with # or // are skipped. The value starts two characters after the first :, so write a space after the colon. A type in parentheses after the key converts the value: (string), (number), (float), (currency), (boolean), (array) (comma-separated), (json), (object) or (eval) (evaluated as JavaScript), (date), (env) (an environment variable), (config) (another CONF key) and (random) (a random string of the given length). def gives default values. onerror(err, line) handles a value that cannot be evaluated; without it the method throws.
var text = 'name : Eshop\nport (number) : 8000\nallow (boolean) : true\nlanguages (array) : en, sk';
var cfg = text.parseConfig({ port: 80 });
// { port: 8000, name: 'Eshop', allow: true, languages: ['en', 'sk'] }
method
String.parseDateExpiration()
Turns a text like 5 minutes into a date in the future.
String.parseDateExpiration()Returns Date The current date plus the given time.
The text is read as pairs of a number and a unit, separated by spaces, for example 1 day 12 hours. Each pair is added to the current date with Date.add(), so the same units work (seconds, minutes, hours, days, weeks, months, years). A pair with the number 0 is ignored.
var expire = '7 days'.parseDateExpiration();
self.cookie('token', token, expire);
'1 day 12 hours'.parseDateExpiration();
method
String.parseUID()
Reads the information stored in an identifier created by UID().
String.parseUID()Returns Object { version, date, century, index, hash, valid }.
The result has version (the last character of the UID), date (when it was created), century, index (the counter), hash and valid. For the random r version (CONF.default_uid = 'r') the result has no date, and identifiers are validated with String.isUID().
var id = UID();
var info = id.parseUID();
console.log(info.date, info.index, info.valid);
method
String.parseFloat2([def])
Finds the first decimal number in a text.
String.parseFloat2([def])| Parameter | Type | Description |
|---|---|---|
def? |
Number |
The value returned when no number is found. Default: 0 |
Returns Number The number found.
Unlike String.parseFloat(), the text may contain other characters: the first group of digits, dots and commas is used, and commas become dots. A leading - makes it negative. Without a number the method returns def.
'Price: 12,50 EUR'.parseFloat2(); // 12.5
'no number'.parseFloat2(-1); // -1
method
String.isGUID()
since 0.0.48
Checks whether the string is a GUID (UUID).
String.isGUID()Returns Boolean
The string must have 36 characters in the form xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx, where M is a version from 1 to 5. Upper and lower case letters are accepted.
'550e8400-e29b-41d4-a716-446655440000'.isGUID(); // true
'550e8400'.isGUID(); // false
method
String.isJSONDate()
Checks whether the string is a date in the JSON (ISO 8601 UTC) format.
String.isJSONDate()Returns Boolean
The method checks the shape of the text, such as 2024-05-01T10:30:00.000Z: the length, the T, the dashes and colons and the final Z. It does not check that the date exists.
var value = '2024-05-01T10:30:00.000Z';
if (value.isJSONDate())
value = new Date(value);
method
String.isNumber([decimal])
Checks whether the string contains only digits.
String.isNumber([decimal])| Parameter | Type | Description |
|---|---|---|
decimal? |
Boolean |
Allow one decimal separator. Default: false |
Returns Boolean
With decimal set to true, one . or , is allowed as well. Signs, spaces and exponents are not accepted, and an empty string returns false.
'12345'.isNumber(); // true
'12.5'.isNumber(); // false
'12.5'.isNumber(true); // true
'-1'.isNumber(); // false
method
String.isBoolean()
Checks whether the string is true or false.
String.isBoolean()Returns Boolean
The comparison ignores case. Other values such as 1 or on return false; String.parseBoolean() reads those.
'TRUE'.isBoolean(); // true
'on'.isBoolean(); // false
method
String.isZIP()
Checks whether the string looks like a postal (ZIP) code.
String.isZIP()Returns Boolean
The string is tested with DEF.validators.zip, by default 3 to 20 letters, digits, spaces or dashes. Change DEF.validators.zip to use your own rule.
'821 08'.isZIP(); // true
'12'.isZIP(); // false
method
String.isXSS()
Checks whether the string contains an HTML tag.
String.isXSS()Returns Boolean
The test is simple: it returns true when the text contains < followed later by >. Use it to reject HTML in plain text fields.
'Hello world'.isXSS(); // false
'<script>alert(1)</script>'.isXSS(); // true
method
String.isSQLInjection()
Checks whether the string contains a quoted text or an SQL keyword.
String.isSQLInjection()Returns Boolean
The method returns true for text in single quotes or for the upper-case words ALTER, CREATE, DELETE, DROP, EXEC, EXECUTE, INSERT, MERGE, SELECT, UPDATE and UNION. It is a rough check; use parameters in your queries anyway.
'shoes'.isSQLInjection(); // false
"1; DROP TABLE users".isSQLInjection(); // true
method
String.isBase64([data])
Checks whether the string is base64 encoded.
String.isBase64([data])| Parameter | Type | Description |
|---|---|---|
data? |
Boolean |
Accept a data URI prefix. Default: false |
Returns Boolean
The length must be divisible by 4 and the text must contain only base64 characters. With data set to true, a data URI such as data:image/png;base64,... is accepted and only the length of the encoded part is checked.
'SGVsbG8='.isBase64(); // true
'data:image/png;base64,iVBORw0K'.isBase64(true); // true
method
String.base64ToFile(filename, [callback])
Writes base64 data to a file.
String.base64ToFile(filename, [callback])| Parameter | Type | Description |
|---|---|---|
filename |
String |
The path of the file. |
callback? |
Function |
Called as callback(err) when the file is written. |
Returns String The same string.
A data URI prefix (everything up to the first comma) is removed, and the rest is decoded and written with fs.writeFile(). The method returns the string itself; the result of writing comes to callback(err).
model.photo.base64ToFile(PATH.public('photos/' + UID() + '.png'), function(err) {
err && console.log(err);
});
method
String.base64ToBuffer()
Decodes base64 data into a Buffer.
String.base64ToBuffer()Returns Buffer The decoded data.
A data URI prefix (everything up to the first comma) is removed before decoding.
var buffer = 'data:text/plain;base64,SGVsbG8='.base64ToBuffer();
buffer.toString(); // Hello
method
String.base64ContentType()
Returns the content type of a data URI.
String.base64ContentType()Returns String The content type, for example image/png.
The text between data: and the first ; is returned. A string without ; returns an empty string.
var type = 'data:image/png;base64,iVBORw0K'.base64ContentType(); // image/png
if (type !== 'image/png' && type !== 'image/jpeg')
$.invalid('@photo');
method
String.crc32([unsigned])
Computes the CRC32 checksum of the string.
String.crc32([unsigned])| Parameter | Type | Description |
|---|---|---|
unsigned? |
Boolean |
Return an unsigned number. Default: false |
Returns Number The checksum.
The result is a signed 32-bit number, or an unsigned one when unsigned is true. String.hash('crc32') and String.hash('crc32unsigned') give the same results.
var checksum = 'Hello world'.crc32(true);
var key = checksum.toString(36);
method
String.sha1([salt])
Creates a SHA-1 hash of the string.
String.sha1([salt])| Parameter | Type | Description |
|---|---|---|
salt? |
String |
Text appended before hashing. |
Returns String The hash as hex.
The salt is appended to the string before hashing.
var hash = 'Hello world'.sha1();
var salted = 'Hello world'.sha1(CONF.secret);
method
String.sha512([salt])
Creates a SHA-512 hash of the string.
String.sha512([salt])| Parameter | Type | Description |
|---|---|---|
salt? |
String |
Text appended before hashing. |
Returns String The hash as hex.
The salt is appended to the string before hashing.
var hash = token.sha512(CONF.secret);
method
String.makeid()
Makes a short id from the string.
String.makeid()Returns String The id.
The id is a quick unsigned hash of the string written in base 36. The same string always gives the same id. It is not a cryptographic hash.
var key = ('products_' + JSON.stringify(query)).makeid();
method
String.sign([key])
since 0.0.81
Adds a quick checksum to the string.
String.sign([key])| Parameter | Type | Description |
|---|---|---|
key? |
String |
A secret mixed into the checksum. |
Returns String The string with the checksum.
The result is the string, a dash and a base 36 hash of the string with key. To verify a value, sign the part before the last dash again and compare. It is a quick checksum, not a cryptographic signature.
var signed = '12345'.sign(CONF.secret); // 12345-xxxxxx
var value = signed.substring(0, signed.lastIndexOf('-'));
var ok = value.sign(CONF.secret) === signed;
method
String.encrypt_uid([key])
Protects an identifier with a checksum.
String.encrypt_uid([key])| Parameter | Type | Description |
|---|---|---|
key? |
String |
The secret. Default: CONF.secret |
Returns String The protected identifier.
The result is x, a checksum and x followed by the original value, so the value stays readable but cannot be changed without the key. The checksum uses key (default CONF.secret) and CONF.secret_uid. Read it back with String.decrypt_uid(). The same function for numbers is U.encrypt_uid(value, [key]).
var token = user.id.encrypt_uid();
var link = '/unsubscribe/?id=' + token;
method
String.decrypt_uid([key])
Reads an identifier protected with String.encrypt_uid().
String.decrypt_uid([key])| Parameter | Type | Description |
|---|---|---|
key? |
String |
The secret used for encrypt_uid(). Default: CONF.secret |
Returns String|Number The original value, or null when the checksum is wrong.
The checksum is created again with key (default CONF.secret). When it matches, the original value is returned, otherwise null. A value created from a number comes back as a number.
var id = (self.query.id || '').decrypt_uid();
if (!id) {
self.invalid('@id');
return;
}
method
String.toName()
Cleans a person name: removes other characters and capitalizes each word.
String.toName()Returns String The cleaned name.
Digits and ASCII punctuation are removed, spaces are kept, and the first letter of each word is made upper case. Letters with diacritics are kept. Trailing spaces are dropped, but leading and repeated spaces are not, so trim the input first.
'peter sirka2'.toName(); // Peter Sirka
"john o'neil".toName(); // John Oneil
method
String.toUnicode()
Escapes characters outside printable ASCII as \uXXXX.
String.toUnicode()Returns String The escaped string.
Characters with a code below 32 or above 126 are written as \u and four hex digits. String.fromUnicode() reverses it.
'Žltý kôň'.toUnicode(); // \u017dlt\u00fd k\u00f4\u0148
method
String.fromUnicode()
Turns \uXXXX escapes back into characters.
String.fromUnicode()Returns String The unescaped string.
Every \u followed by four hex digits is replaced with the character. It reverses String.toUnicode().
'\\u017dlt\\u00fd'.fromUnicode(); // Žltý
method
String.endsWith(text, [ignoreCase])
Checks whether the string ends with a text.
String.endsWith(text, [ignoreCase])| Parameter | Type | Description |
|---|---|---|
text |
String |
The text to find. |
ignoreCase? |
Boolean|Number |
true to ignore case, or an offset from the end. Default: false |
Returns Boolean
Total.js replaces the native method. With ignoreCase set to true, case is ignored. A number in place of ignoreCase checks the text that many characters before the end.
'Photo.JPG'.endsWith('.jpg', true); // true
'Photo.JPG'.endsWith('.jpg'); // false
method
String.replacer(find, text)
Replaces the first occurrence of a text, without regular expressions.
String.replacer(find, text)| Parameter | Type | Description |
|---|---|---|
find |
String |
The text to replace. |
text |
String |
The new text. |
Returns String The new string.
find is plain text, so characters like $ or . have no special meaning in it or in text. When find is not found, the string is returned unchanged.
'Total: {price}'.replacer('{price}', '$ 25'); // Total: $ 25
method
String.insert(index, value)
Inserts a value at a position in the string.
String.insert(index, value)| Parameter | Type | Description |
|---|---|---|
index |
Number |
The position. |
value |
Object |
The value to insert. |
Returns String The new string.
The value is converted to a string with toString().
'ABCDEF'.insert(3, '-'); // ABC-DEF
method
String.indent(count, [char])
Adds a character to the start of the string a number of times.
String.indent(count, [char])| Parameter | Type | Description |
|---|---|---|
count |
Number |
How many characters to add. |
char? |
String |
The character. Default: ' ' |
Returns String The indented string.
Unlike String.padLeft(), the characters are always added, whatever the length of the string.
'item'.indent(2, '\t'); // \t\titem
'item'.indent(4); // ' item'
method
String.pluralize(zero, one, few, other)
Chooses a word form by the number in the string.
String.pluralize(zero, one, few, other)| Parameter | Type | Description |
|---|---|---|
zero |
String |
The form for 0, or all forms separated by commas. |
one? |
String |
The form for 1. |
few? |
String |
The form for 2 to 4. |
other? |
String |
The form for other numbers. |
Returns String The chosen form.
The string is read with String.parseInt() and passed to Number.pluralize(), so the rules and the # placeholder are the same.
var count = self.query.count || '0';
count.pluralize('no items', '# item', '# items', '# items');
method
String.env()
Replaces [key] placeholders with configuration values.
String.env()Returns String The string with the values.
Every [key] (letters, digits and _) is replaced with CONF[key]; a missing key gives an empty string.
// CONF.url = 'https://www.example.com'
'[url]/api/products/'.env(); // https://www.example.com/api/products/
method
String.streamer(beg, [end], callback, [skip])
since 0.0.63
Finds blocks in a string and passes each to a callback.
String.streamer(beg, [end], callback, [skip])| Parameter | Type | Description |
|---|---|---|
beg |
String |
The start delimiter, or the separator when end is missing. |
end? |
String |
The end delimiter. |
callback |
Function |
Called as callback(value, index); return false to stop. |
skip? |
Number |
The number of blocks to skip. Default: 0 |
Returns undefined
With beg and end, every block that starts with beg and ends with end is passed, delimiters included. Without end, the string is split after every beg, and each part ends with beg. callback(value, index) can return false to stop. skip skips the first blocks.
var xml = '<items><item>A</item><item>B</item></items>';
xml.streamer('<item>', '</item>', function(value, index) {
console.log(index, value); // 0 <item>A</item>, 1 <item>B</item>
});
method
Number.fixed(decimals)
Rounds the number to a number of decimals and returns a number.
Number.fixed(decimals)| Parameter | Type | Description |
|---|---|---|
decimals |
Number |
The number of decimals. |
Returns Number The rounded number.
The same as +number.toFixed(decimals): unlike toFixed(), the result is a number, not a string.
(12.3456).fixed(2); // 12.35
method
Number.currency([currency], [a], [b], [c])
Formats the number with a currency formatter from DEF.currencies.
Number.currency([currency], [a], [b], [c])| Parameter | Type | Description |
|---|---|---|
currency? |
String |
The key in DEF.currencies. Default: 'default' |
a? |
Object |
Passed to the formatter, like b and c. |
Returns String The formatted price.
DEF.currencies is empty by default; add a function function(value, a, b, c) for each currency code you need, and default for calls without a code. The extra arguments are passed to it. Without a formatter the number is formatted with Number.format(2).
DEF.currencies.eur = function(value) {
return value.format(2, ' ', ',') + ' €';
};
DEF.currencies.usd = function(value) {
return '$' + value.format(2);
};
(1250.5).currency('eur'); // 1 250,50 €
method
Number.hex([length])
Converts the number to upper-case hexadecimal.
Number.hex([length])| Parameter | Type | Description |
|---|---|---|
length? |
Number |
The minimum length. |
Returns String The hex value.
The result is padded with leading zeros to length characters.
(255).hex(); // FF
(10).hex(2); // 0A
method
Number.parseDate([plus])
Creates a date from a timestamp in milliseconds.
Number.parseDate([plus])| Parameter | Type | Description |
|---|---|---|
plus? |
Number |
Milliseconds to add. Default: 0 |
Returns Date The date.
plus milliseconds are added to the number before the date is created.
var created = (1714559400000).parseDate();
var tomorrow = Date.now().parseDate(24 * 60 * 60 * 1000);
method
Number.toRad()
Converts degrees to radians.
Number.toRad()Returns Number The angle in radians.
Defined only when Number.prototype.toRad does not exist yet.
var dlat = (lat2 - lat1).toRad();
var dlon = (lon2 - lon1).toRad();
method
Date.parseDate()
Returns the date itself.
Date.parseDate()Returns Date The same date.
It lets you call parseDate() on a value that can be a string, a number or a date, without checking its type first.
var value = model.date; // String, Number or Date
var date = value.parseDate();