---
title: Prototypes
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/prototypes/
updated: 2026-11-16T15:41:15.818Z
---

# Prototypes

> Methods of String, Number, Date and Array added by Total.js 4.

Methods that Total.js 4 adds to `String`, `Number`, `Date` and `Array`. The guide [Prototypes](../../guides/prototypes/) explains how to use them with examples; this page is the exact reference.

## API

### String.format([arg0], [arg1], [...])

Type: `method`

Replaces indexed placeholders `{0}`, `{1}`... with the arguments.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `arg0` | `Object` | no |  | 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()`.

Example: Indexed placeholders
```js
var text = 'Hello {0}, you have {1} new messages.'.format('Peter', 5);
// Hello Peter, you have 5 new messages.
```

### String.args(obj, [encode], [def])

Type: `method`

Replaces named placeholders `{key}` or `{{key}}` with values of an object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | The values. |
| `encode` | `Boolean|String|Function` | no |  | `true` (URL encoding), `'html'`, `'json'` or a function `function(value, key)`. |
| `def` | `String` | no |  | 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.

Example: Named placeholders
```js
var model = { name: 'Peter', city: 'Bratislava' };
var text = 'Hello {name} from {{city}}'.args(model);
// Hello Peter from Bratislava
```

Example: HTML encoding
```js
var html = '<b>{name}</b>'.args({ name: '<Peter>' }, 'html');
// <b>&lt;Peter&gt;</b>
```

Example: A default for missing values
```js
'{name} ({age})'.args({ name: 'Peter' }, null, '-');
// Peter (-)
```

### String.slug([max])

Type: `method`

Creates a URL-friendly slug from the text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | no | `60` | The maximum length. |

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.

Example: Slug from a title
```js
var slug = 'Hello World: Total.js 4'.slug();
// hello-world-total-js-4
```

### String.max(length, [chars])

Type: `method`

Cuts the text to a maximum length and adds an ellipsis.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | The maximum length of the result. |
| `chars` | `String` | no | `'...'` | The text appended to a cut string. |

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.

Example: Shorten a description
```js
'A long description'.max(10);
// A long ...
```

### String.capitalize([first])

Type: `method`

Upper-cases the first letter of every word.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `first` | `Boolean` | no | `false` | Capitalize only the first letter. |

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.

Example: Words and first letter
```js
'hello WORLD'.capitalize();	 // Hello World
'hello WORLD'.capitalize(true); // Hello world
```

### String.parseInt([def])

Type: `method`

Converts the whole string to a number.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Number` | no | `0` | The value returned when the string is not a number. |

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()`.

Example: Query parameter
```js
var page = (this.query.page || '').parseInt(1);
'42'.parseInt();	 // 42
'abc'.parseInt(-1); // -1
```

### String.parseInt2([def])

Type: `method`

Reads the first integer found in the text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Number` | no | `0` | The value returned when the text contains no number. |

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).

Example: Number inside text
```js
'Width: 120px'.parseInt2();   // 120
'Price: 12,50 EUR'.parseFloat2(); // 12.5
```

### String.parseFloat([def])

Type: `method`

Converts the string to a decimal number.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Number` | no | `0` | The value returned when the string is not a number. |

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.

Example: Decimal comma
```js
'12,5'.parseFloat();  // 12.5
'x'.parseFloat(0.1); // 0.1
```

### String.parseBoolean()

Type: `method`

Converts `true`, `1` or `on` to `true`.

Returns: `Boolean`

The comparison ignores case. Every other value gives `false`.

Example: Checkbox value
```js
var enabled = (this.body.enabled || '').parseBoolean();
'ON'.parseBoolean(); // true
```

### String.parseDate([format])

Type: `method`

Converts the string to a `Date`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `format` | `String` | no |  | 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.

Example: Parse dates
```js
var a = '2024-01-15 10:30'.parseDate();
var b = '15/01/2024'.parseDate('dd/MM/yyyy');
```

### String.parseJSON([date])

Type: `method`

Parses JSON without throwing an exception.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `Boolean` | no | `false` | Convert ISO date strings to dates. |

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.

Example: Safe parse
```js
var obj = '{"name":"Peter","created":"2024-01-15T10:30:00.000Z"}'.parseJSON(true);
// obj.created instanceof Date === true
var bad = '{name'.parseJSON(); // undefined
```

### String.parseENV()

Type: `method`

Parses `KEY=value` lines (the `.env` format) into an object.

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.

Example: Read a .env file
```js
require('fs').readFile(PATH.root('.env'), 'utf8', function(err, text) {
	if (!err) {
		var env = text.parseENV();
		console.log(env.DATABASE);
	}
});
```

### String.isEmail()

Type: `method`

Checks whether the string is an email address.

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`.

Example: Validate input
```js
if (!this.body.email.isEmail()) {
	this.invalid('Invalid email');
	return;
}
```

### String.isPhone()

Type: `method`

Checks whether the string is a phone number.

Returns: `Boolean`

The test uses the `DEF.validators.phone` regular expression. Strings shorter than 6 characters are always `false`.

Example: Phone number
```js
'+421903123456'.isPhone(); // true
```

### String.isURL()

Type: `method`

Checks whether the string is a URL address.

Returns: `Boolean`

The test uses the `DEF.validators.url` regular expression. Strings of 7 characters or less are always `false`.

Example: URL address
```js
'https://www.totaljs.com'.isURL(); // true
```

### String.isUID()

Type: `method`

Checks whether the string is a valid identifier created by `UID()`.

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.

Example: Validate an id from the URL
```js
function detail(id) {
	if (!id.isUID()) {
		this.throw404();
		return;
	}
	// ...
}
```

### String.isJSON()

Type: `method`

Checks whether the string looks like JSON.

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.

Example: Quick test
```js
'{"a":1}'.isJSON(); // true
'hello'.isJSON();   // false
```

### String.hash([type], [salt])

Type: `method`

Creates a hash of the string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String|Boolean` | no |  | The algorithm, or `true` for an unsigned number hash. |
| `salt` | `String` | no |  | 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.

Example: Different hashes
```js
'hello'.hash();		  // a 32-bit number
'hello'.hash(true);	  // an unsigned 32-bit number
'hello'.hash('sha256');  // a hex string
'hello'.hash('crc32unsigned');
```

### String.md5([salt])

Type: `method`

Returns the MD5 hash as a hex string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `salt` | `String` | no |  | 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.

Example: Cache key
```js
var key = JSON.stringify(this.query).md5();
```

### String.sha256([salt])

Type: `method`

Returns the SHA-256 hash as a hex string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `salt` | `String` | no |  | 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.

Example: Hash with a salt
```js
var hash = model.password.sha256(CONF.secret);
var short = 'hello'.sha1();
var long = 'hello'.sha512();
```

### String.encode()

Type: `method`

Encodes HTML special characters.

Returns: `String` The encoded text.

Replaces `<`, `>`, `"`, `'` and `&` with HTML entities, so the text can be written safely into HTML.

Example: Escape user input
```js
'<script>alert("x")</script>'.encode();
// &lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;
```

### String.decode()

Type: `method`

Decodes HTML entities back to characters.

Returns: `String` The decoded text.

Named entities and numeric entities (`&#65;`, `&#x41;`) are converted. It is the opposite of `String.encode()`.

Example: Decode
```js
'&lt;b&gt;Hello&lt;/b&gt;'.decode(); // <b>Hello</b>
```

### String.encrypt(key, [isUnique], [secret])

Type: `method`

Encrypts the string with a key.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The encryption key. |
| `isUnique` | `Boolean` | no | `false` | Make every result different. |
| `secret` | `String` | no | `CONF.secret` | An additional 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.

Example: Encrypt a token
```js
var token = JSON.stringify({ id: user.id }).encrypt('my-key', true);
```

### String.decrypt(key, [secret])

Type: `method`

Decrypts a string created by `String.encrypt()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The encryption key. |
| `secret` | `String` | no | `CONF.secret` | The additional 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`.

Example: Decrypt a token
```js
var data = (this.query.token || '').decrypt('my-key');
var obj = data ? data.parseJSON() : null;
```

### String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])

Type: `method`

Extracts keywords from the text, sorted by frequency.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `forSearch` | `Boolean` | no | `true` | Normalize the words for search. |
| `alternative` | `Boolean` | no | `false` | Shorten every word to 80% of its length. |
| `max_count` | `Number` | no | `200` | The maximum number of words read. |
| `max_length` | `Number` | no | `20` | The maximum length of a word. |
| `min_length` | `Number` | no | `2` | The minimum length of a word. |

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.

Example: Keywords for a search index
```js
var words = (item.name + ' ' + item.description).keywords();
item.search = words.join(' ');
```

### String.toSearch()

Type: `method`

Normalizes the text for a full-text search.

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.

Example: Search value
```js
var q = (this.query.q || '').toSearch();
```

### String.toASCII()

Type: `method`

Removes diacritics from the text.

Returns: `String` The text without diacritics.

Accented letters are replaced with their basic Latin letters, for example `á` with `a`.

Example: Remove diacritics
```js
'Žltý kôň'.toASCII(); // Zlty kon
```

### String.removeTags()

Type: `method`

Removes HTML tags from the text.

Returns: `String` The plain text.

Only the tags are removed; the text between them stays. HTML entities are not decoded.

Example: Plain text
```js
'<p>Hello <b>world</b></p>'.removeTags(); // Hello world
```

### String.padLeft(max, [c])

Type: `method`

Pads the string on the left to the length `max`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | The final length. |
| `c` | `String` | no | `' '` | The padding character. |

Returns: `String` The padded string.

A string that is already `max` characters or longer is returned unchanged.

Example: Leading zeros
```js
'7'.padLeft(3, '0'); // 007
```

### String.padRight(max, [c])

Type: `method`

Pads the string on the right to the length `max`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | The final length. |
| `c` | `String` | no | `' '` | The padding character. |

Returns: `String` The padded string.

A string that is already `max` characters or longer is returned unchanged.

Example: Fixed-width column
```js
'Name'.padRight(10) + '|'; // 'Name	  |'
```

### String.startsWith(text, [ignoreCase])

Type: `method`

Checks whether the string starts with `text`, optionally ignoring case.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | yes |  | The text to find. |
| `ignoreCase` | `Boolean|Number` | no |  | `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.

Example: Ignore case
```js
'Hello World'.startsWith('hello', true); // true
'photo.JPG'.endsWith('.jpg', true);	 // true
```

### String.markdown([opt])

Type: `method` · Since: `0.0.92`

Converts Markdown to HTML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `opt` | `Object` | no |  | 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).

Example: Render Markdown
```js
var html = '# Title\n\nSome **bold** text.'.markdown();
```

Example: Without wrapper and images
```js
var html = text.markdown({ wrap: false, images: false });
```

### String.tslash()

Type: `method` · Since: `0.0.95`

Removes trailing slashes.

Returns: `String` The string without trailing slashes.

All `/` characters at the end are removed, but a single `/` is kept, so `'/'` stays `'/'`.

Example: Clean a URL
```js
'https://www.totaljs.com/'.tslash(); // https://www.totaljs.com
'/products//'.tslash();			// /products
```

### String.toJSONSchema([name], [url])

Type: `method`

Creates a JSON schema object from an inline definition.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | The name of the schema used in `$id`. |
| `url` | `String` | no | `CONF.url` | The base URL of `$id`. |

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`.

Example: Inline schema
```js
var schema = '*name:string(50), *email:email, age:number, tags:[string], status:{draft|published}'.toJSONSchema('user');
// schema.required: ['name', 'email']
```

### Number.format([decimals], [separator], [separatorDecimal])

Type: `method`

Formats the number with a thousands separator and decimals.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimals` | `Number` | no |  | The number of decimals. |
| `separator` | `String` | no | `' '` | The thousands separator. |
| `separatorDecimal` | `String` | no | `'.'` | The decimal separator. |

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)`.

Example: Format prices
```js
(1234567.891).format(2);		   // 1 234 567.89
(1234.5).format(2, '.');		  // 1.234,50
(1234.5).format(2, ',', '.');	 // 1,234.50
```

### Number.pluralize(zero, one, few, other)

Type: `method`

Chooses a word form by the number.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `zero` | `String` | yes |  | The form for 0, or all forms separated by commas. |
| `one` | `String` | no |  | The form for 1. |
| `few` | `String` | no |  | The form for 2 to 4. |
| `other` | `String` | no |  | 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.

Example: Item count
```js
var count = 3;
count.pluralize('no items', '# item', '# items', '# items'); // 3 items
count.pluralize('no items,# item,# items,# items');		  // 3 items
```

### Number.padLeft(max, [c])

Type: `method`

Converts the number to a string padded on the left.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | The final length. |
| `c` | `String` | no | `'0'` | The padding character. |

Returns: `String` The padded number.

The default padding character is `0`.

Example: Invoice number
```js
(42).padLeft(6); // 000042
```

### Number.padRight(max, [c])

Type: `method`

Converts the number to a string padded on the right.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | The final length. |
| `c` | `String` | no | `'0'` | The padding character. |

Returns: `String` The padded number.

The default padding character is `0`.

Example: Pad right
```js
(42).padRight(5); // 42000
```

### Number.round([precision])

Type: `method`

Rounds the number to a number of decimals.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `precision` | `Number` | no | `0` | The number of decimals. |

Returns: `Number` The rounded number.

Without `precision` the number is rounded to an integer.

Example: Round
```js
(3.14159).round(2); // 3.14
(2.5).round();	  // 3
```

### Number.floor(decimals)

Type: `method`

Rounds the number down to a number of decimals.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimals` | `Number` | yes |  | The number of decimals. |

Returns: `Number` The number rounded down.

It works like `Math.floor()` with decimals.

Example: Floor
```js
(3.14959).floor(2); // 3.14
```

### Number.between(condition, otherwise)

Type: `method`

Returns a value from a map of number ranges.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `condition` | `Object` | yes |  | Ranges as keys and results as values. |
| `otherwise` | `Object` | yes |  | 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`.

Example: Rating label
```js
var label = (4).between({ '1-2': 'bad', '3-4': 'good', '5-': 'excellent' }, 'none');
// good
```

### Number.add(value, [decimals])

Type: `method`

Applies a math operation written as a string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Number|String` | yes |  | A number, or an operation such as `'-5'` or `'+20%'`. |
| `decimals` | `Number` | no |  | 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.

Example: Operations
```js
(100).add('+20%'); // 120
(100).add('-5');   // 95
(100).add('*2');   // 200
```

### Number.VAT(percentage, [decimals], [includedVAT])

Type: `method`

Adds VAT to the price, or removes it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `percentage` | `Number` | yes |  | The VAT rate in percent. |
| `decimals` | `Number` | no | `2` | The number of decimals. |
| `includedVAT` | `Boolean` | no | `false` | The number already includes VAT. |

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`.

Example: With and without VAT
```js
(100).VAT(20);		  // 120
(120).VAT(20, 2, true); // 100
```

### Number.discount(percentage, [decimals])

Type: `method`

Subtracts a percentage discount.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `percentage` | `Number` | yes |  | The discount in percent. |
| `decimals` | `Number` | no | `2` | The number of decimals. |

Returns: `Number` The discounted number.

The result is rounded down to `decimals`.

Example: Discount
```js
(80).discount(15); // 68
```

### Number.filesize([decimals], [type])

Type: `method`

Formats a number of bytes as a readable file size.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimals` | `Number` | no |  | The number of decimals. |
| `type` | `String` | no |  | 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.

Example: File size
```js
(1536).filesize();		 // 1.50 KB
(5242880).filesize(0, 'MB'); // 5 MB
```

### Number.async(fn, [callback])

Type: `method`

Runs an asynchronous function the number of times, counting down.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | The function `function(number, next)`. |
| `callback` | `Function` | no |  | 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.

Example: Three runs
```js
(3).async(function(number, next) {
	console.log(number); // 3, 2, 1
	setTimeout(next, 100);
}, function() {
	console.log('Done');
});
```

### Date.add(type, [value])

Type: `method`

Returns a new date moved by a time period.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String|Number` | yes |  | The unit, an expression such as `'5 days'`, or milliseconds. |
| `value` | `Number` | no |  | 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.

Example: Move dates
```js
var expire = NOW.add('1 month');
var yesterday = NOW.add('days', -1);
var later = NOW.add('2 hours');
```

### Date.format([format], [resource])

Type: `method`

Formats the date as a string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `format` | `String` | no |  | The format, for example `'dd.MM.yyyy HH:mm'`. |
| `resource` | `String` | no |  | 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.

Example: Formats
```js
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
```

### Date.diff([date], type)

Type: `method`

Returns the difference between two dates in a unit.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `Date|Number|String` | no | `now` | The date to compare with. |
| `type` | `String` | yes |  | 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`.

Example: Days left
```js
var left = item.expire.diff('days');
var age = NOW.diff(user.dtcreated, 'hours');
```

### Date.toUTC([ticks])

Type: `method`

Shifts the date by the local timezone offset.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ticks` | `Boolean` | no | `false` | Return milliseconds. |

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.

Example: UTC date
```js
var utc = new Date().toUTC();
var ticks = new Date().toUTC(true);
```

### Date.extend(date)

Type: `method`

Returns a new date with parts set from a string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `String` | yes |  | 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.

Example: Set time
```js
var noon = NOW.extend('12:00');
var eve = NOW.extend('2024-12-24 18:00');
```

### Date.setTimeZone(timezone)

Type: `method`

Returns a new date converted to a timezone.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `timezone` | `String` | yes |  | The IANA timezone name. |

Returns: `Date` A new date.

The `timezone` is an IANA name such as `'Europe/Bratislava'`.

Example: Time in New York
```js
var dt = new Date().setTimeZone('America/New_York');
```

### Array.findItem(cb, [value])

Type: `method`

Returns the first matching item, or `null`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String` | yes |  | A function or a property name. |
| `value` | `Object` | no |  | 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.

Example: By property and by function
```js
var user = users.findItem('id', id);
var admin = users.findItem(item => item.role === 'admin');
```

### Array.findAll(cb, [value])

Type: `method`

Returns all matching items.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String` | yes |  | A function `function(item, index)` or a property name. |
| `value` | `Object` | no |  | 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.

Example: Filter
```js
var active = users.findAll('active', true);
var adults = users.findAll(item => item.age >= 18);
```

### Array.findIndex(cb, [value])

Type: `method`

Returns the index of the first matching item, or `-1`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String` | yes |  | A function or a property name. |
| `value` | `Object` | no |  | 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.

Example: Index by property
```js
var index = users.findIndex('id', id);
if (index !== -1)
	users.splice(index, 1);
```

### Array.TfindIndex(cb, [value])

Type: `method` · Since: `0.0.95`

An alias of `Array.findIndex()` that other modules do not override.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String` | yes |  | A function or a property name. |
| `value` | `Object` | no |  | 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.

Example: Safe index
```js
var index = users.TfindIndex('id', id);
```

### Array.findValue(cb, value, path, [def])

Type: `method`

Finds an item and returns one of its properties.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String` | yes |  | A function or a property name. |
| `value` | `Object` | yes |  | The value of the property. |
| `path` | `String` | yes |  | The property to return. |
| `def` | `Object` | no |  | 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.

Example: Name by id
```js
var name = users.findValue('id', id, 'name', 'Unknown');
```

### Array.remove(cb, [value])

Type: `method`

Returns a new array without the matching items.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String|Object` | yes |  | A function, a property name or an item. |
| `value` | `Object` | no |  | 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.

Example: Remove items
```js
users = users.remove('id', id);
numbers = [1, 2, 3, 2].remove(2); // [1, 3]
```

### Array.take(count)

Type: `method`

Returns the first `count` items.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | The number of items. |

Returns: `Array` A new array.

The result is a new array.

Example: First three
```js
[1, 2, 3, 4, 5].take(3); // [1, 2, 3]
```

### Array.skip(count)

Type: `method`

Returns the items after the first `count` items.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | The number of skipped items. |

Returns: `Array` A new array.

Together with `Array.take()` it makes simple paging.

Example: Paging
```js
var page = 2;
var limit = 10;
var items = all.skip((page - 1) * limit).take(limit);
```

### Array.first([def])

Type: `method`

Returns the first item, or `def` for an empty array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Object` | no |  | The value for an empty array. |

Returns: `Object`

Example: First item
```js
var item = response.items.first(null);
```

### Array.last([def])

Type: `method`

Returns the last item, or `def` for an empty array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Object` | no |  | The value for an empty array. |

Returns: `Object`

Example: Last item
```js
[1, 2, 3].last(); // 3
```

### Array.quicksort([sort], [desc])

Type: `method`

Sorts the array in place.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sort` | `String|Boolean` | no |  | The properties to sort by, or `true` for descending primitive values. |
| `desc` | `Boolean` | no | `false` | Sort descending. |

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.

Example: Sort objects
```js
products.quicksort('price_desc');
products.quicksort('category,name');
users.quicksort('dtcreated', true);
```

### Array.toObject([name])

Type: `method`

Creates an object (a lookup map) from the array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | 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`.

Example: Lookups
```js
var byid = users.toObject('id');
var user = byid[id];

var allowed = ['admin', 'editor'].toObject();
// { admin: true, editor: true }
```

### Array.trim()

Type: `method`

Trims strings and removes empty items.

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.

Example: Clean a list
```js
'a, b, ,c'.split(',').trim(); // ['a', 'b', 'c']
```

### Array.wait(onItem, [callback], [thread])

Type: `method`

Processes items one by one with an asynchronous function.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `onItem` | `Function` | yes |  | The function `function(item, next, index)`. |
| `callback` | `Function` | no |  | Called after the last item. |
| `thread` | `Number|Boolean` | no | `1` | The number of parallel items, or `true` to remove items. |

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'`.

Example: Send emails one by one
```js
users.wait(function(user, next) {
	MAIL(user.email, 'News', '=mails/news', user, next);
}, function() {
	console.log('All sent');
});
```

### Array.async([thread], [callback])

Type: `method`

Runs an array of asynchronous functions.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `thread` | `Number` | no | `1` | The number of parallel functions. |
| `callback` | `Function` | no |  | 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')`.

Example: A list of tasks
```js
var tasks = [];

tasks.push(function(next) {
	// load something
	next();
});

tasks.push(function(next) {
	// save something
	next();
});

tasks.async(function() {
	console.log('Done');
});
```

### Array.limit(max, fn, [callback])

Type: `method`

Processes the array in chunks of `max` items.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | The size of a chunk. |
| `fn` | `Function` | yes |  | The function `function(items, next, beg, end)`. |
| `callback` | `Function` | no |  | 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.

Example: Insert in batches
```js
rows.limit(100, function(items, next) {
	// insert 100 items at once
	next();
}, function() {
	console.log('Imported');
});
```

### Array.random([item])

Type: `method`

Shuffles the array, or returns a random item.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `item` | `Boolean` | no | `false` | Return one random item. |

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.

Example: Shuffle and pick
```js
var deck = [1, 2, 3, 4, 5].random();
var winner = users.random(true);
```

### String.parseCSV([delimiter])

Type: `method`

Parses CSV text into an array of objects.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `delimiter` | `String` | no | `','` | The column delimiter. |

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.

Example: Read a CSV file
```js
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(';');
```

### String.parseUA([structured])

Type: `method`

Reads the operating system, browser and device type from a user agent string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `structured` | `Boolean` | no | `false` | Return an object instead of a text. |

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.

Example: Detect the client
```js
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);
```

### String.parseEncoded()

Type: `method`

Parses `application/x-www-form-urlencoded` text into an object.

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`.

Example: Parse a form body
```js
var data = 'name=Peter+Sirka&tags=a&tags=b&city=Bratislava%2C%20SK'.parseEncoded();
// { name: 'Peter Sirka', tags: 'a,b', city: 'Bratislava, SK' }
```

### String.parseXML([replace])

Type: `method`

Parses XML into a flat object of paths and values.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `replace` | `Boolean` | no | `false` | Replace special characters in the keys with `_`. |

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 `_`.

Example: Read an XML feed
```js
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' }
```

### String.parseHTML([trim])

Type: `method` · Since: `0.0.67`

Parses HTML into a tree of elements that you can search and change.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `trim` | `Boolean` | no | `false` | Trim the text content. |

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.

Example: Read and change HTML
```js
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());
```

### String.parseComponent(tags)

Type: `method`

Cuts tagged blocks out of a text and returns their content by name.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `tags` | `Object` | yes |  | 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.

Example: Split a component file
```js
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);'
```

### String.parseTerminal([fields], fn, [skip], [take])

Type: `method`

Parses the column output of a terminal command line by line.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fields` | `Array` | no |  | Header names or regular expressions of the columns. |
| `fn` | `Function` | yes |  | Called as `fn(values, index, count, line)` for every line. |
| `skip` | `Number` | no | `0` | The number of lines to skip. |
| `take` | `Number` | no | `all` | The number of lines to read. |

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.

Example: Read the output of df
```js
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]);
	});
});
```

### String.parseConfig([def], [onerror])

Type: `method`

Parses text in the Total.js config format into an object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Object` | no |  | Default values copied into the result. |
| `onerror` | `Function` | no |  | 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.

Example: Parse a config text
```js
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'] }
```

### String.parseDateExpiration()

Type: `method`

Turns a text like `5 minutes` into a date in the future.

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.

Example: Expiration of a cookie
```js
var expire = '7 days'.parseDateExpiration();
self.cookie('token', token, expire);

'1 day 12 hours'.parseDateExpiration();
```

### String.parseUID()

Type: `method`

Reads the information stored in an identifier created by `UID()`.

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()`.

Example: When was a record created
```js
var id = UID();
var info = id.parseUID();
console.log(info.date, info.index, info.valid);
```

### String.parseFloat2([def])

Type: `method`

Finds the first decimal number in a text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Number` | no | `0` | The value returned when no number is found. |

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`.

Example: Price from a label
```js
'Price: 12,50 EUR'.parseFloat2();	// 12.5
'no number'.parseFloat2(-1);		// -1
```

### String.isGUID()

Type: `method` · Since: `0.0.48`

Checks whether the string is a GUID (UUID).

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.

Example: Validate a UUID
```js
'550e8400-e29b-41d4-a716-446655440000'.isGUID();	// true
'550e8400'.isGUID();								// false
```

### String.isJSONDate()

Type: `method`

Checks whether the string is a date in the JSON (ISO 8601 UTC) format.

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.

Example: Revive dates
```js
var value = '2024-05-01T10:30:00.000Z';
if (value.isJSONDate())
	value = new Date(value);
```

### String.isNumber([decimal])

Type: `method`

Checks whether the string contains only digits.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimal` | `Boolean` | no | `false` | Allow one decimal separator. |

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`.

Example: Check user input
```js
'12345'.isNumber();		// true
'12.5'.isNumber();		// false
'12.5'.isNumber(true);	// true
'-1'.isNumber();		// false
```

### String.isBoolean()

Type: `method`

Checks whether the string is `true` or `false`.

Returns: `Boolean`

The comparison ignores case. Other values such as `1` or `on` return `false`; `String.parseBoolean()` reads those.

Example: Check a query value
```js
'TRUE'.isBoolean();	// true
'on'.isBoolean();	// false
```

### String.isZIP()

Type: `method`

Checks whether the string looks like a postal (ZIP) code.

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.

Example: Validate a postal code
```js
'821 08'.isZIP();	// true
'12'.isZIP();		// false
```

### String.isXSS()

Type: `method`

Checks whether the string contains an HTML tag.

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.

Example: Reject HTML
```js
'Hello world'.isXSS();				// false
'<script>alert(1)</script>'.isXSS();	// true
```

### String.isSQLInjection()

Type: `method`

Checks whether the string contains a quoted text or an SQL keyword.

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.

Example: Check a search phrase
```js
'shoes'.isSQLInjection();					// false
"1; DROP TABLE users".isSQLInjection();	// true
```

### String.isBase64([data])

Type: `method`

Checks whether the string is base64 encoded.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Boolean` | no | `false` | Accept a data URI prefix. |

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.

Example: Check an upload
```js
'SGVsbG8='.isBase64();						// true
'data:image/png;base64,iVBORw0K'.isBase64(true);	// true
```

### String.base64ToFile(filename, [callback])

Type: `method`

Writes base64 data to a file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | The path of the file. |
| `callback` | `Function` | no |  | 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)`.

Example: Save an uploaded image
```js
model.photo.base64ToFile(PATH.public('photos/' + UID() + '.png'), function(err) {
	err && console.log(err);
});
```

### String.base64ToBuffer()

Type: `method`

Decodes base64 data into a `Buffer`.

Returns: `Buffer` The decoded data.

A data URI prefix (everything up to the first comma) is removed before decoding.

Example: Decode a data URI
```js
var buffer = 'data:text/plain;base64,SGVsbG8='.base64ToBuffer();
buffer.toString(); // Hello
```

### String.base64ContentType()

Type: `method`

Returns the content type of a data URI.

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.

Example: Check the type of an upload
```js
var type = 'data:image/png;base64,iVBORw0K'.base64ContentType(); // image/png
if (type !== 'image/png' && type !== 'image/jpeg')
	$.invalid('@photo');
```

### String.crc32([unsigned])

Type: `method`

Computes the CRC32 checksum of the string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `unsigned` | `Boolean` | no | `false` | Return an unsigned number. |

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.

Example: Checksum of a text
```js
var checksum = 'Hello world'.crc32(true);
var key = checksum.toString(36);
```

### String.sha1([salt])

Type: `method`

Creates a SHA-1 hash of the string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `salt` | `String` | no |  | Text appended before hashing. |

Returns: `String` The hash as hex.

The `salt` is appended to the string before hashing.

Example: SHA-1 hash
```js
var hash = 'Hello world'.sha1();
var salted = 'Hello world'.sha1(CONF.secret);
```

### String.sha512([salt])

Type: `method`

Creates a SHA-512 hash of the string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `salt` | `String` | no |  | Text appended before hashing. |

Returns: `String` The hash as hex.

The `salt` is appended to the string before hashing.

Example: Hash a token
```js
var hash = token.sha512(CONF.secret);
```

### String.makeid()

Type: `method`

Makes a short id from the string.

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.

Example: Id for a cache key
```js
var key = ('products_' + JSON.stringify(query)).makeid();
```

### String.sign([key])

Type: `method` · Since: `0.0.81`

Adds a quick checksum to the string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | no |  | 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.

Example: Sign and verify a value
```js
var signed = '12345'.sign(CONF.secret); // 12345-xxxxxx

var value = signed.substring(0, signed.lastIndexOf('-'));
var ok = value.sign(CONF.secret) === signed;
```

### String.encrypt_uid([key])

Type: `method`

Protects an identifier with a checksum.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | no | `CONF.secret` | The 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])`.

Example: Protected id in a link
```js
var token = user.id.encrypt_uid();
var link = '/unsubscribe/?id=' + token;
```

### String.decrypt_uid([key])

Type: `method`

Reads an identifier protected with `String.encrypt_uid()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | no | `CONF.secret` | The secret used for `encrypt_uid()`. |

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.

Example: Verify a link
```js
var id = (self.query.id || '').decrypt_uid();
if (!id) {
	self.invalid('@id');
	return;
}
```

### String.toName()

Type: `method`

Cleans a person name: removes other characters and capitalizes each word.

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.

Example: Clean a name from a form
```js
'peter sirka2'.toName();	// Peter Sirka
"john o'neil".toName();	// John Oneil
```

### String.toUnicode()

Type: `method`

Escapes characters outside printable ASCII as `\uXXXX`.

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.

Example: Escape a text
```js
'Žltý kôň'.toUnicode(); // \u017dlt\u00fd k\u00f4\u0148
```

### String.fromUnicode()

Type: `method`

Turns `\uXXXX` escapes back into characters.

Returns: `String` The unescaped string.

Every `\u` followed by four hex digits is replaced with the character. It reverses `String.toUnicode()`.

Example: Unescape a text
```js
'\\u017dlt\\u00fd'.fromUnicode(); // Žltý
```

### String.endsWith(text, [ignoreCase])

Type: `method`

Checks whether the string ends with a text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | yes |  | The text to find. |
| `ignoreCase` | `Boolean|Number` | no | `false` | `true` to ignore case, or an offset from the end. |

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.

Example: Check a file extension
```js
'Photo.JPG'.endsWith('.jpg', true);	// true
'Photo.JPG'.endsWith('.jpg');		// false
```

### String.replacer(find, text)

Type: `method`

Replaces the first occurrence of a text, without regular expressions.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `find` | `String` | yes |  | The text to replace. |
| `text` | `String` | yes |  | 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.

Example: Insert a price into a template
```js
'Total: {price}'.replacer('{price}', '$ 25'); // Total: $ 25
```

### String.insert(index, value)

Type: `method`

Inserts a value at a position in the string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `index` | `Number` | yes |  | The position. |
| `value` | `Object` | yes |  | The value to insert. |

Returns: `String` The new string.

The value is converted to a string with `toString()`.

Example: Format a code
```js
'ABCDEF'.insert(3, '-'); // ABC-DEF
```

### String.indent(count, [char])

Type: `method`

Adds a character to the start of the string a number of times.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | How many characters to add. |
| `char` | `String` | no | `' '` | The character. |

Returns: `String` The indented string.

Unlike `String.padLeft()`, the characters are always added, whatever the length of the string.

Example: Indent a line
```js
'item'.indent(2, '\t'); // \t\titem
'item'.indent(4);		// '    item'
```

### String.pluralize(zero, one, few, other)

Type: `method`

Chooses a word form by the number in the string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `zero` | `String` | yes |  | The form for 0, or all forms separated by commas. |
| `one` | `String` | no |  | The form for 1. |
| `few` | `String` | no |  | The form for 2 to 4. |
| `other` | `String` | no |  | 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.

Example: Count from a query
```js
var count = self.query.count || '0';
count.pluralize('no items', '# item', '# items', '# items');
```

### String.env()

Type: `method`

Replaces `[key]` placeholders with configuration values.

Returns: `String` The string with the values.

Every `[key]` (letters, digits and `_`) is replaced with `CONF[key]`; a missing key gives an empty string.

Example: Build a URL from the config
```js
// CONF.url = 'https://www.example.com'
'[url]/api/products/'.env(); // https://www.example.com/api/products/
```

### String.streamer(beg, [end], callback, [skip])

Type: `method` · Since: `0.0.63`

Finds blocks in a string and passes each to a callback.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `beg` | `String` | yes |  | The start delimiter, or the separator when `end` is missing. |
| `end` | `String` | no |  | The end delimiter. |
| `callback` | `Function` | yes |  | Called as `callback(value, index)`; return `false` to stop. |
| `skip` | `Number` | no | `0` | The number of blocks to skip. |

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.

Example: Read items from XML
```js
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>
});
```

### Number.fixed(decimals)

Type: `method`

Rounds the number to a number of decimals and returns a number.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimals` | `Number` | yes |  | 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.

Example: Round a price
```js
(12.3456).fixed(2); // 12.35
```

### Number.currency([currency], [a], [b], [c])

Type: `method`

Formats the number with a currency formatter from `DEF.currencies`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `currency` | `String` | no | `'default'` | The key in `DEF.currencies`. |
| `a` | `Object` | no |  | 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)`.

Example: Register and use currencies
```js
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 €
```

### Number.hex([length])

Type: `method`

Converts the number to upper-case hexadecimal.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | no |  | The minimum length. |

Returns: `String` The hex value.

The result is padded with leading zeros to `length` characters.

Example: Color component
```js
(255).hex();	// FF
(10).hex(2);	// 0A
```

### Number.parseDate([plus])

Type: `method`

Creates a date from a timestamp in milliseconds.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `plus` | `Number` | no | `0` | Milliseconds to add. |

Returns: `Date` The date.

`plus` milliseconds are added to the number before the date is created.

Example: Date from a timestamp
```js
var created = (1714559400000).parseDate();
var tomorrow = Date.now().parseDate(24 * 60 * 60 * 1000);
```

### Number.toRad()

Type: `method`

Converts degrees to radians.

Returns: `Number` The angle in radians.

Defined only when `Number.prototype.toRad` does not exist yet.

Example: Distance between two GPS points
```js
var dlat = (lat2 - lat1).toRad();
var dlon = (lon2 - lon1).toRad();
```

### Date.parseDate()

Type: `method`

Returns the date itself.

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.

Example: Value of an unknown type
```js
var value = model.date; // String, Number or Date
var date = value.parseDate();
```
