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

# Prototipi

> Metodi di String, Number, Date e Array aggiunti da Total.js 4.

Metodi che Total.js 4 aggiunge a `String`, `Number`, `Date` e `Array`. La guida [Prototipi](../../guides/prototypes/) spiega come usarli con esempi; questa pagina è il riferimento esatto.

## API

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

Type: `method`

Sostituisce i segnaposto indicizzati `{0}`, `{1}`... con gli argomenti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `arg0` | `Object` | no |  | Il valore per `{0}`. Può seguire un numero qualsiasi di argomenti. |

Returns: `String` La stringa formattata.

Ogni `{n}` viene sostituito con l'argomento all'indice `n`. Un argomento `null` o `undefined` produce una stringa vuota. Per i segnaposto con nome usa `String.args()`.

Example: Segnaposto indicizzati
```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`

Sostituisce i segnaposto con nome `{key}` o `{{key}}` con i valori di un oggetto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | I valori. |
| `encode` | `Boolean|String|Function` | no |  | `true` (codifica URL), `'html'`, `'json'` o una funzione `function(value, key)`. |
| `def` | `String` | no |  | Il testo per un valore mancante. Viene ignorato quando `encode` è una stringa. |

Returns: `String` La stringa con i valori.

Le chiavi possono contenere lettere, numeri, `_`, `$`, `.` e `-`. Un valore mancante mantiene il segnaposto, oppure usa `def` quando lo imposti.

L'argomento `encode` cambia il modo in cui vengono scritti i valori: `true` li codifica con `encodeURIComponent()`, `'html'` codifica le entità HTML, `'json'` scrive `JSON.stringify(value)` e una funzione `function(value, key)` restituisce il testo stesso. `String.arg()` è un alias.

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

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

Example: Un valore predefinito per i valori mancanti
```js
'{name} ({age})'.args({ name: 'Peter' }, null, '-');
// Peter (-)
```

### String.slug([max])

Type: `method`

Crea uno slug adatto agli URL a partire dal testo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | no | `60` | La lunghezza massima. |

Returns: `String` Lo slug.

Il testo viene privato degli spazi esterni, convertito in minuscolo e in ASCII (senza segni diacritici). Spazi e punteggiatura diventano un unico `-`; un `-` finale viene rimosso. Il risultato viene tagliato a `max` caratteri.

Quando il testo non ha caratteri latini utilizzabili (per esempio cinese o cirillico), il metodo restituisce invece un breve hash costruito dal testo.

Example: Slug da un titolo
```js
var slug = 'Hello World: Total.js 4'.slug();
// hello-world-total-js-4
```

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

Type: `method`

Taglia il testo a una lunghezza massima e aggiunge i puntini di sospensione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | La lunghezza massima del risultato. |
| `chars` | `String` | no | `'...'` | Il testo aggiunto a una stringa tagliata. |

Returns: `String` Il testo accorciato.

Quando il testo è più lungo di `length`, viene tagliato in modo che il risultato con `chars` abbia esattamente `length` caratteri. Un testo più corto viene restituito invariato.

Example: Accorciare una descrizione
```js
'A long description'.max(10);
// A long ...
```

### String.capitalize([first])

Type: `method`

Rende maiuscola la prima lettera di ogni parola.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `first` | `Boolean` | no | `false` | Rendere maiuscola solo la prima lettera. |

Returns: `String` Il testo con le iniziali maiuscole.

Il testo viene convertito in minuscolo e ogni lettera dopo uno spazio, una tabulazione o un a capo diventa maiuscola. Con `first` impostato su `true`, diventa maiuscola solo la prima lettera dell'intero testo.

Example: Parole e prima lettera
```js
'hello WORLD'.capitalize();	 // Hello World
'hello WORLD'.capitalize(true); // Hello world
```

### String.parseInt([def])

Type: `method`

Converte l'intera stringa in un numero.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Number` | no | `0` | Il valore restituito quando la stringa non è un numero. |

Returns: `Number` Il numero, oppure `def`.

La stringa viene privata degli spazi esterni e convertita con l'operatore unario `+`, quindi l'intera stringa deve essere un numero: `'12px'` non è un numero e restituisce `def`. Per leggere un numero da un testo più lungo, usa `String.parseInt2()`.

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

### String.parseInt2([def])

Type: `method`

Legge il primo intero trovato nel testo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Number` | no | `0` | Il valore restituito quando il testo non contiene numeri. |

Returns: `Number` Il numero, oppure `def`.

A differenza di `String.parseInt()`, il numero può essere circondato da altro testo. Un `-` iniziale viene mantenuto. `String.parseFloat2()` funziona allo stesso modo per i numeri decimali (è accettato il separatore decimale `,`).

Example: Numero all'interno del testo
```js
'Width: 120px'.parseInt2();   // 120
'Price: 12,50 EUR'.parseFloat2(); // 12.5
```

### String.parseFloat([def])

Type: `method`

Converte la stringa in un numero decimale.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Number` | no | `0` | Il valore restituito quando la stringa non è un numero. |

Returns: `Number` Il numero, oppure `def`.

La stringa viene privata degli spazi esterni e un separatore decimale `,` viene sostituito con `.`. L'intera stringa deve essere un numero, altrimenti viene restituito `def`.

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

### String.parseBoolean()

Type: `method`

Converte `true`, `1` o `on` in `true`.

Returns: `Boolean`

Il confronto non distingue tra maiuscole e minuscole. Qualsiasi altro valore restituisce `false`.

Example: Valore di una checkbox
```js
var enabled = (this.body.enabled || '').parseBoolean();
'ON'.parseBoolean(); // true
```

### String.parseDate([format])

Type: `method`

Converte la stringa in un `Date`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `format` | `String` | no |  | Il formato dell'input, per esempio `'dd/MM/yyyy'`. |

Returns: `Date` La data analizzata.

Senza `format`, il metodo legge stringhe ISO (`2024-01-15T10:30:00.000Z`), `yyyy-MM-dd HH:mm:ss`, `dd.MM.yyyy HH:mm` e qualsiasi valore che `new Date()` comprende. Una parte della data mancante usa la data odierna.

Con `format`, le cifre della stringa vengono lette nell'ordine delle lettere del formato (`yyyy`, `MM`, `dd`, `HH`, `mm`, `ss`). Un `pm` nel testo aggiunge 12 ore.

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

### String.parseJSON([date])

Type: `method`

Analizza un JSON senza sollevare eccezioni.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `Boolean` | no | `false` | Convertire le stringhe di data ISO in date. |

Returns: `Object` Il valore analizzato, oppure `undefined` per un JSON non valido.

Un JSON non valido restituisce `undefined` invece di un errore. Con `date` impostato su `true`, le stringhe di data ISO vengono convertite in oggetti `Date`.

Example: Analisi sicura
```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`

Analizza righe `KEY=value` (il formato `.env`) e le trasforma in un oggetto.

Returns: `Object` Le chiavi e i loro valori stringa.

Le righe vuote e quelle che iniziano con `#` o `//` vengono saltate. I valori tra virgolette doppie o singole perdono le virgolette, e `\n` diventa un a capo. I valori senza virgolette vengono privati degli spazi esterni.

Example: Leggere un file .env
```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`

Verifica se la stringa è un indirizzo email.

Returns: `Boolean`

Il test usa l'espressione regolare `DEF.validators.email`, quindi puoi sostituirla. Le stringhe di 4 caratteri o meno sono sempre `false`.

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

### String.isPhone()

Type: `method`

Verifica se la stringa è un numero di telefono.

Returns: `Boolean`

Il test usa l'espressione regolare `DEF.validators.phone`. Le stringhe più corte di 6 caratteri sono sempre `false`.

Example: Numero di telefono
```js
'+421903123456'.isPhone(); // true
```

### String.isURL()

Type: `method`

Verifica se la stringa è un indirizzo URL.

Returns: `Boolean`

Il test usa l'espressione regolare `DEF.validators.url`. Le stringhe di 7 caratteri o meno sono sempre `false`.

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

### String.isUID()

Type: `method`

Verifica se la stringa è un identificatore valido creato da `UID()`.

Returns: `Boolean`

Il metodo verifica il formato con `DEF.validators.uid` e poi il checksum che `UID()` scrive in ogni identificatore, quindi una stringa casuale con i caratteri giusti non viene accettata.

Example: Validare un id dall'URL
```js
function detail(id) {
	if (!id.isUID()) {
		this.throw404();
		return;
	}
	// ...
}
```

### String.isJSON()

Type: `method`

Verifica se la stringa sembra un JSON.

Returns: `Boolean`

Vengono controllati solo il primo e l'ultimo carattere non bianco: `{...}`, `[...]`, `"..."` o un numero. Il contenuto non viene analizzato; per questo usa `String.parseJSON()`.

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

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

Type: `method`

Crea un hash della stringa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String|Boolean` | no |  | L'algoritmo, oppure `true` per un hash numerico senza segno. |
| `salt` | `String` | no |  | Testo aggiunto prima del calcolo dell'hash. |

Returns: `String|Number` Una stringa esadecimale per md5/sha*, altrimenti un numero.

`type` sceglie l'algoritmo: `'md5'`, `'sha1'`, `'sha256'`, `'sha512'` (stringhe esadecimali), `'crc32'` o `'crc32unsigned'` (numeri). Senza tipo, il metodo restituisce un hash numerico veloce a 32 bit; `true` lo rende senza segno. Il `salt` viene aggiunto alla stringa prima del calcolo dell'hash.

Example: Hash diversi
```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`

Restituisce l'hash MD5 come stringa esadecimale.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `salt` | `String` | no |  | Testo aggiunto prima del calcolo dell'hash. |

Returns: `String` Una stringa esadecimale di 32 caratteri.

Il `salt` viene aggiunto alla stringa prima del calcolo dell'hash. Usalo per checksum e chiavi di cache, non per le password.

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

### String.sha256([salt])

Type: `method`

Restituisce l'hash SHA-256 come stringa esadecimale.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `salt` | `String` | no |  | Testo aggiunto prima del calcolo dell'hash. |

Returns: `String` Una stringa esadecimale di 64 caratteri.

Il `salt` viene aggiunto alla stringa prima del calcolo dell'hash. `String.sha1([salt])` e `String.sha512([salt])` funzionano allo stesso modo con gli altri algoritmi.

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

### String.encode()

Type: `method`

Codifica i caratteri speciali HTML.

Returns: `String` Il testo codificato.

Sostituisce `<`, `>`, `"`, `'` e `&` con entità HTML, così il testo può essere scritto in modo sicuro nell'HTML.

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

### String.decode()

Type: `method`

Decodifica le entità HTML riportandole a caratteri.

Returns: `String` Il testo decodificato.

Vengono convertite le entità con nome e quelle numeriche (`&#65;`, `&#x41;`). È l'opposto di `String.encode()`.

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

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

Type: `method`

Cifra la stringa con una chiave.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | La chiave di cifratura. |
| `isUnique` | `Boolean` | no | `false` | Rendere diverso ogni risultato. |
| `secret` | `String` | no | `CONF.secret` | Un segreto aggiuntivo. |

Returns: `String` La stringa cifrata.

Con `isUnique` impostato su `true`, ogni chiamata dà un risultato diverso per lo stesso input. Il risultato contiene un checksum creato da `secret` (predefinito `CONF.secret`) e dalla chiave, che `String.decrypt()` verifica. Usalo per token e URL, non per salvare password.

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

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

Type: `method`

Decifra una stringa creata da `String.encrypt()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | La chiave di cifratura. |
| `secret` | `String` | no | `CONF.secret` | Il segreto aggiuntivo. |

Returns: `String` La stringa originale, oppure `null`.

Usa la stessa `key` e lo stesso `secret` della cifratura. Una chiave errata, un segreto errato o una stringa modificata restituiscono `null`.

Example: Decifrare un 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`

Estrae le parole chiave dal testo, ordinate per frequenza.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `forSearch` | `Boolean` | no | `true` | Normalizzare le parole per la ricerca. |
| `alternative` | `Boolean` | no | `false` | Accorciare ogni parola all'80% della sua lunghezza. |
| `max_count` | `Number` | no | `200` | Il numero massimo di parole lette. |
| `max_length` | `Number` | no | `20` | La lunghezza massima di una parola. |
| `min_length` | `Number` | no | `2` | La lunghezza minima di una parola. |

Returns: `String[]` Parole univoche, prima le più frequenti.

Con `forSearch` (predefinito `true`) il testo viene convertito in ASCII e `y` diventa `i`, il che rende la ricerca più tollerante. Con `alternative`, ogni parola viene accorciata all'80% della sua lunghezza. Le parole più corte di `min_length` o più lunghe di `max_length` vengono saltate. `String.toKeywords()` è un alias.

Example: Parole chiave per un indice di ricerca
```js
var words = (item.name + ' ' + item.description).keywords();
item.search = words.join(' ');
```

### String.toSearch()

Type: `method`

Normalizza il testo per una ricerca full-text.

Returns: `String` Il testo normalizzato.

Il testo viene convertito in minuscolo e in ASCII, i caratteri speciali vengono rimossi, `y` diventa `i` e le lettere ripetute vengono unite. Applicalo sia al testo salvato sia alla frase cercata.

Example: Valore di ricerca
```js
var q = (this.query.q || '').toSearch();
```

### String.toASCII()

Type: `method`

Rimuove i segni diacritici dal testo.

Returns: `String` Il testo senza segni diacritici.

Le lettere accentate vengono sostituite con le loro lettere latine di base, per esempio `á` con `a`.

Example: Rimuovere i segni diacritici
```js
'Žltý kôň'.toASCII(); // Zlty kon
```

### String.removeTags()

Type: `method`

Rimuove i tag HTML dal testo.

Returns: `String` Il testo semplice.

Vengono rimossi solo i tag; il testo tra di essi resta. Le entità HTML non vengono decodificate.

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

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

Type: `method`

Riempie la stringa a sinistra fino alla lunghezza `max`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | La lunghezza finale. |
| `c` | `String` | no | `' '` | Il carattere di riempimento. |

Returns: `String` La stringa riempita.

Una stringa che ha già `max` caratteri o più viene restituita invariata.

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

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

Type: `method`

Riempie la stringa a destra fino alla lunghezza `max`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | La lunghezza finale. |
| `c` | `String` | no | `' '` | Il carattere di riempimento. |

Returns: `String` La stringa riempita.

Una stringa che ha già `max` caratteri o più viene restituita invariata.

Example: Colonna a larghezza fissa
```js
'Name'.padRight(10) + '|'; // 'Name	  |'
```

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

Type: `method`

Verifica se la stringa inizia con `text`, eventualmente ignorando maiuscole e minuscole.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | yes |  | Il testo da cercare. |
| `ignoreCase` | `Boolean|Number` | no |  | `true` per ignorare maiuscole e minuscole, oppure una posizione iniziale. |

Returns: `Boolean`

Total.js sostituisce il metodo nativo. Con `ignoreCase` impostato su `true` il confronto ignora maiuscole e minuscole; un numero viene usato come posizione iniziale. `String.endsWith(text, [ignoreCase])` funziona allo stesso modo alla fine della stringa.

Example: Ignorare maiuscole e minuscole
```js
'Hello World'.startsWith('hello', true); // true
'photo.JPG'.endsWith('.jpg', true);	 // true
```

### String.markdown([opt])

Type: `method` · Since: `0.0.92`

Converte Markdown in HTML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `opt` | `Object` | no |  | Le opzioni descritte sopra. |

Returns: `String` L'HTML.

Il risultato viene racchiuso in `<div class="markdown markdown-container">` a meno che `opt.wrap` sia `false`. La maggior parte delle funzionalità è attiva per impostazione predefinita e ne disattivi una con `false`: `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `headlines`, `hr`, `blockquotes`, `sections`, `footnotes`, `urlify`, `keywords`, `emptynewline`, `bookmarks`. Altre opzioni: `linetag` (il tag di un paragrafo, predefinito `'p'`), `prefix` (un prefisso per gli id generati), `custom` (una funzione che modifica ogni riga) e `html` (una funzione `function(html, type)` che modifica l'HTML generato).

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

Example: Senza contenitore e senza immagini
```js
var html = text.markdown({ wrap: false, images: false });
```

### String.tslash()

Type: `method` · Since: `0.0.95`

Rimuove gli slash finali.

Returns: `String` La stringa senza slash finali.

Tutti i caratteri `/` alla fine vengono rimossi, ma un singolo `/` viene mantenuto, quindi `'/'` resta `'/'`.

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

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

Type: `method`

Crea un oggetto schema JSON da una definizione inline.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | Il nome dello schema usato in `$id`. |
| `url` | `String` | no | `CONF.url` | L'URL di base di `$id`. |

Returns: `Object` Lo schema JSON.

La definizione è un elenco di coppie `name:type` separate da virgole o da a capo. Un `*` o `!` prima del nome rende il campo obbligatorio. Tipi: `string`, `email`, `phone`, `url`, `uid`, `name`, `zip`, `lower`, `upper`, `capitalize`, `color`, `icon`, `base64`, `number`, `int`, `float`, `boolean`, `date`, `object`. `string(50)` imposta una lunghezza massima, `[string]` crea un array, `{draft|published}` un enum e `@name` usa un altro schema.

L'`$id` viene costruito da `url` (predefinito `CONF.url`) e `name`.

Example: Schema inline
```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`

Formatta il numero con un separatore delle migliaia e i decimali.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimals` | `Number` | no |  | Il numero di decimali. |
| `separator` | `String` | no | `' '` | Il separatore delle migliaia. |
| `separatorDecimal` | `String` | no | `'.'` | Il separatore decimale. |

Returns: `String` Il numero formattato.

Il separatore delle migliaia predefinito è uno spazio. I decimali vengono troncati (non arrotondati) o completati con zeri fino a `decimals`. Il separatore decimale è `.`, oppure `,` quando il separatore delle migliaia è `.`. Puoi anche passare prima il separatore: `format(',', 2)`.

Example: Formattare i prezzi
```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`

Sceglie la forma di una parola in base al numero.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `zero` | `String` | yes |  | La forma per 0, oppure tutte le forme separate da virgole. |
| `one` | `String` | no |  | La forma per 1. |
| `few` | `String` | no |  | La forma da 2 a 4. |
| `other` | `String` | no |  | La forma per gli altri numeri. |

Returns: `String` La forma scelta.

`zero` si usa per 0, `one` per 1, `few` da 2 a 4 e `other` per il resto. Un `#` nella forma scelta viene sostituito con il numero. Puoi anche passare tutte le forme come un'unica stringa separata da virgole.

Example: Numero di elementi
```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`

Converte il numero in una stringa riempita a sinistra.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | La lunghezza finale. |
| `c` | `String` | no | `'0'` | Il carattere di riempimento. |

Returns: `String` Il numero riempito.

Il carattere di riempimento predefinito è `0`.

Example: Numero di fattura
```js
(42).padLeft(6); // 000042
```

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

Type: `method`

Converte il numero in una stringa riempita a destra.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | La lunghezza finale. |
| `c` | `String` | no | `'0'` | Il carattere di riempimento. |

Returns: `String` Il numero riempito.

Il carattere di riempimento predefinito è `0`.

Example: Riempimento a destra
```js
(42).padRight(5); // 42000
```

### Number.round([precision])

Type: `method`

Arrotonda il numero a un certo numero di decimali.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `precision` | `Number` | no | `0` | Il numero di decimali. |

Returns: `Number` Il numero arrotondato.

Senza `precision` il numero viene arrotondato a un intero.

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

### Number.floor(decimals)

Type: `method`

Arrotonda il numero per difetto a un certo numero di decimali.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimals` | `Number` | yes |  | Il numero di decimali. |

Returns: `Number` Il numero arrotondato per difetto.

Funziona come `Math.floor()` con i decimali.

Example: Arrotondamento per difetto
```js
(3.14959).floor(2); // 3.14
```

### Number.between(condition, otherwise)

Type: `method`

Restituisce un valore da una mappa di intervalli numerici.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `condition` | `Object` | yes |  | Intervalli come chiavi e risultati come valori. |
| `otherwise` | `Object` | yes |  | Il valore quando nessun intervallo corrisponde. |

Returns: `Object` Il valore dell'intervallo corrispondente.

Le chiavi di `condition` sono intervalli: `'1-5'` (da 1 a 5), `'10-'` (10 e oltre) o `'-5'` (5 e meno). Viene restituito il valore del primo intervallo corrispondente, altrimenti `otherwise`.

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

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

Type: `method`

Applica un'operazione matematica scritta come stringa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Number|String` | yes |  | Un numero, oppure un'operazione come `'-5'` o `'+20%'`. |
| `decimals` | `Number` | no |  | Arrotondare il risultato per difetto a questi decimali. |

Returns: `Number` Il risultato.

Un numero viene sommato. Una stringa inizia con un operatore `+`, `-`, `*` o `/` seguito da un numero, per esempio `'+10'`. Con `%` alla fine l'operando è una percentuale del numero: `'+20%'` aggiunge il 20%. Con `decimals` il risultato viene arrotondato per difetto a quel numero di decimali.

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

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

Type: `method`

Aggiunge l'IVA al prezzo, oppure la rimuove.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `percentage` | `Number` | yes |  | L'aliquota IVA in percentuale. |
| `decimals` | `Number` | no | `2` | Il numero di decimali. |
| `includedVAT` | `Boolean` | no | `false` | Il numero include già l'IVA. |

Returns: `Number` Il prezzo.

Senza `includedVAT` il metodo restituisce il prezzo con IVA. Con `includedVAT` impostato su `true`, il numero è un prezzo con IVA e il metodo restituisce il prezzo senza IVA. Il risultato viene arrotondato a `decimals`.

Example: Con e senza IVA
```js
(100).VAT(20);		  // 120
(120).VAT(20, 2, true); // 100
```

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

Type: `method`

Sottrae uno sconto in percentuale.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `percentage` | `Number` | yes |  | Lo sconto in percentuale. |
| `decimals` | `Number` | no | `2` | Il numero di decimali. |

Returns: `Number` Il numero scontato.

Il risultato viene arrotondato per difetto a `decimals`.

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

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

Type: `method`

Formatta un numero di byte come dimensione di file leggibile.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimals` | `Number` | no |  | Il numero di decimali. |
| `type` | `String` | no |  | L'unità: `'bytes'`, `'KB'`, `'MB'`, `'GB'` o `'TB'`. |

Returns: `String` La dimensione con l'unità.

Senza `type` l'unità viene scelta automaticamente (`bytes`, `KB`, `MB`, `GB` o `TB`). Con `type` il valore viene convertito in quell'unità. Senza `decimals` il valore ha fino a 2 decimali.

Example: Dimensione del file
```js
(1536).filesize();		 // 1.50 KB
(5242880).filesize(0, 'MB'); // 5 MB
```

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

Type: `method`

Esegue una funzione asincrona il numero indicato di volte, con un conto alla rovescia.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | La funzione `function(number, next)`. |
| `callback` | `Function` | no |  | Chiamata dopo l'ultima esecuzione. |

Returns: `Number`

La funzione riceve il numero corrente (dal valore iniziale fino a 1) e `next`. L'esecuzione successiva inizia dopo che chiami `next()`. Quando il conteggio arriva a zero, viene chiamata `callback`.

Example: Tre esecuzioni
```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`

Restituisce una nuova data spostata di un periodo di tempo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String|Number` | yes |  | L'unità, un'espressione come `'5 days'`, oppure millisecondi. |
| `value` | `Number` | no |  | La quantità. |

Returns: `Date` Una nuova data.

Passa un tipo e un valore (`add('days', 5)`) o un'unica espressione (`add('5 days')`). Tipi: `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`, anche nelle forme brevi `s`, `m`, `h`, `d`, `w`, `M`, `y`. I valori negativi spostano indietro. Un numero aggiunge millisecondi. La data originale non viene modificata.

Example: Spostare le date
```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`

Formatta la data come stringa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `format` | `String` | no |  | Il formato, per esempio `'dd.MM.yyyy HH:mm'`. |
| `resource` | `String` | no |  | Il file di risorse con i nomi tradotti di mesi e giorni. |

Returns: `String` La data formattata.

Senza `format` la data viene restituita come stringa ISO in UTC. I token di formato usano l'ora locale: `yyyy`, `yy`, `MM`, `M`, `MMM` (nome breve del mese), `MMMM` (nome del mese), `dd`, `d`, `ddd` (nome breve del giorno), `dddd` (nome del giorno), `HH`, `H`, `mm`, `m`, `ss`, `s`, `ww` (settimana ISO), `a` (AM/PM). I nomi di mesi e giorni sono in inglese; con `resource` vengono letti da quel file di risorse.

Example: Formati
```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`

Restituisce la differenza tra due date in un'unità.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `Date|Number|String` | no | `now` | La data con cui confrontare. |
| `type` | `String` | yes |  | L'unità. |

Returns: `Number` La differenza.

La differenza è `this - date`, arrotondata per eccesso. Senza `date` il metodo confronta con l'istante attuale. Unità: `seconds`, `minutes`, `hours`, `days`, `months`, `years` e le forme brevi `s`, `m`, `h`, `d`, `M`, `y`. Un mese vale 28 giorni. Un'unità sconosciuta restituisce `NaN`.

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

### Date.toUTC([ticks])

Type: `method`

Sposta la data dell'offset del fuso orario locale.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ticks` | `Boolean` | no | `false` | Restituire millisecondi. |

Returns: `Date|Number`

Il risultato mostra l'ora UTC nei campi locali della data. Con `ticks` impostato su `true`, il metodo restituisce millisecondi invece di una data.

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

### Date.extend(date)

Type: `method`

Restituisce una nuova data con alcune parti impostate da una stringa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `String` | yes |  | Le parti di data o ora, per esempio `'12:00'` o `'2024-12-24 18:00'`. |

Returns: `Date` Una nuova data.

La stringa può contenere una data (`yyyy-MM-dd` o `dd.MM.yyyy`) e un'ora (`HH:mm` o `HH:mm:ss`). Vengono modificate solo le parti indicate; sono impostate in UTC.

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

### Date.setTimeZone(timezone)

Type: `method`

Restituisce una nuova data convertita in un fuso orario.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `timezone` | `String` | yes |  | Il nome IANA del fuso orario. |

Returns: `Date` Una nuova data.

`timezone` è un nome IANA come `'Europe/Bratislava'`.

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

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

Type: `method`

Restituisce il primo elemento corrispondente, oppure `null`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String` | yes |  | Una funzione o il nome di una proprietà. |
| `value` | `Object` | no |  | Il valore della proprietà. |

Returns: `Object` L'elemento, oppure `null`.

`cb` è una funzione `function(item, index)`, oppure il nome di una proprietà confrontata con `value` (`===`). Con un unico argomento che non è una funzione vengono confrontati gli elementi stessi.

Example: Per proprietà e per funzione
```js
var user = users.findItem('id', id);
var admin = users.findItem(item => item.role === 'admin');
```

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

Type: `method`

Restituisce tutti gli elementi corrispondenti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String` | yes |  | Una funzione `function(item, index)` o il nome di una proprietà. |
| `value` | `Object` | no |  | Il valore della proprietà. |

Returns: `Array` Gli elementi corrispondenti.

Gli argomenti sono gli stessi di `Array.findItem()`. Il risultato è un nuovo array.

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

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

Type: `method`

Restituisce l'indice del primo elemento corrispondente, oppure `-1`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String` | yes |  | Una funzione o il nome di una proprietà. |
| `value` | `Object` | no |  | Il valore della proprietà. |

Returns: `Number` L'indice, oppure `-1`.

Total.js sostituisce il metodo nativo in modo che accetti anche il nome di una proprietà e un valore. Una funzione viene chiamata come `function(item, index)`. `Array.TfindIndex()` è lo stesso metodo con un nome che gli altri moduli non sovrascrivono.

Example: Indice per proprietà
```js
var index = users.findIndex('id', id);
if (index !== -1)
	users.splice(index, 1);
```

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

Type: `method` · Since: `0.0.95`

Un alias di `Array.findIndex()` che gli altri moduli non sovrascrivono.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String` | yes |  | Una funzione o il nome di una proprietà. |
| `value` | `Object` | no |  | Il valore della proprietà. |

Returns: `Number` L'indice, oppure `-1`.

Alcuni moduli NPM sostituiscono `Array.prototype.findIndex` con una propria versione. In quel caso `TfindIndex()` mantiene il comportamento di Total.js (nome di proprietà e valore). `findItem()` e `findValue()` lo usano internamente.

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

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

Type: `method`

Trova un elemento e ne restituisce una proprietà.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String` | yes |  | Una funzione o il nome di una proprietà. |
| `value` | `Object` | yes |  | Il valore della proprietà. |
| `path` | `String` | yes |  | La proprietà da restituire. |
| `def` | `Object` | no |  | Il valore predefinito. |

Returns: `Object` Il valore della proprietà, oppure `def`.

L'elemento viene trovato come in `Array.findItem()`; poi viene restituita la sua proprietà `path`. Quando non c'è alcun elemento o la proprietà è `null`/`undefined`, viene restituito `def`.

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

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

Type: `method`

Restituisce un nuovo array senza gli elementi corrispondenti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String|Object` | yes |  | Una funzione, il nome di una proprietà o un elemento. |
| `value` | `Object` | no |  | Il valore della proprietà. |

Returns: `Array` Un nuovo array.

Gli argomenti sono gli stessi di `Array.findItem()`. L'array originale non viene modificato, quindi assegna il risultato.

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

### Array.take(count)

Type: `method`

Restituisce i primi `count` elementi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | Il numero di elementi. |

Returns: `Array` Un nuovo array.

Il risultato è un nuovo array.

Example: I primi tre
```js
[1, 2, 3, 4, 5].take(3); // [1, 2, 3]
```

### Array.skip(count)

Type: `method`

Restituisce gli elementi che seguono i primi `count` elementi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | Il numero di elementi saltati. |

Returns: `Array` Un nuovo array.

Insieme ad `Array.take()` permette una semplice paginazione.

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

### Array.first([def])

Type: `method`

Restituisce il primo elemento, oppure `def` per un array vuoto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Object` | no |  | Il valore per un array vuoto. |

Returns: `Object`

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

### Array.last([def])

Type: `method`

Restituisce l'ultimo elemento, oppure `def` per un array vuoto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Object` | no |  | Il valore per un array vuoto. |

Returns: `Object`

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

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

Type: `method`

Ordina l'array sul posto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sort` | `String|Boolean` | no |  | Le proprietà in base a cui ordinare, oppure `true` per valori primitivi in ordine decrescente. |
| `desc` | `Boolean` | no | `false` | Ordinare in modo decrescente. |

Returns: `Array` Lo stesso array.

`sort` è il nome di una proprietà con un suffisso facoltativo `_asc` o `_desc`, per esempio `'name'` o `'price_desc'`. Più proprietà sono separate da virgole (`'name_asc,price_desc'`) e le proprietà annidate usano i punti. Stringhe, numeri, booleani e date vengono confrontati in base al loro tipo. Con `desc` impostato su `true`, l'ordine viene invertito.

Senza argomenti, i valori primitivi vengono ordinati in modo crescente; `quicksort(true)` li ordina in modo decrescente.

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

### Array.toObject([name])

Type: `method`

Crea un oggetto (una mappa di lookup) dall'array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | La proprietà usata come chiave. |

Returns: `Object` L'oggetto di lookup.

Con `name`, ogni elemento viene salvato sotto il valore della sua proprietà `name`. Senza di esso, ogni elemento diventa una chiave con il valore `true`.

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

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

### Array.trim()

Type: `method`

Rimuove gli spazi esterni dalle stringhe ed elimina gli elementi vuoti.

Returns: `Array` Un nuovo array.

Le stringhe vengono private degli spazi esterni, e gli elementi vuoti dopo questa operazione (o che sono `null`, `0`, `false`) vengono rimossi. Restituisce un nuovo array.

Example: Pulire un elenco
```js
'a, b, ,c'.split(',').trim(); // ['a', 'b', 'c']
```

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

Type: `method`

Elabora gli elementi uno alla volta con una funzione asincrona.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `onItem` | `Function` | yes |  | La funzione `function(item, next, index)`. |
| `callback` | `Function` | no |  | Chiamata dopo l'ultimo elemento. |
| `thread` | `Number|Boolean` | no | `1` | Il numero di elementi in parallelo, oppure `true` per rimuovere gli elementi. |

Returns: `Array` Lo stesso array.

`onItem(item, next, index)` viene chiamata per ogni elemento; chiama `next()` per continuare. `callback` viene chiamata dopo l'ultimo elemento. `thread` imposta quanti elementi vengono elaborati contemporaneamente (predefinito 1). Con `thread` impostato su `true`, gli elementi vengono rimossi dall'array mentre vengono elaborati. Chiama `next('cancel')` per fermarti; `callback` riceve allora `'cancel'`.

Example: Inviare email una alla volta
```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`

Esegue un array di funzioni asincrone.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `thread` | `Number` | no | `1` | Il numero di funzioni in parallelo. |
| `callback` | `Function` | no |  | Chiamata alla fine. |

Returns: `Array` Lo stesso array.

Ogni elemento è una funzione `function(next)`. Gli elementi vengono rimossi dall'array mentre vengono eseguiti. `thread` imposta quante funzioni vengono eseguite contemporaneamente (predefinito 1). `callback` viene chiamata dopo l'ultima funzione, oppure con `'cancel'` quando una funzione chiama `next('cancel')`.

Example: Un elenco di attività
```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`

Elabora l'array a blocchi di `max` elementi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | La dimensione di un blocco. |
| `fn` | `Function` | yes |  | La funzione `function(items, next, beg, end)`. |
| `callback` | `Function` | no |  | Chiamata dopo l'ultimo blocco. |

Returns: `Array` Lo stesso array.

`fn(items, next, beg, end)` riceve il blocco successivo; chiama `next()` per continuare con il blocco seguente. `callback` viene chiamata dopo l'ultimo blocco.

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

### Array.random([item])

Type: `method`

Mescola l'array, oppure restituisce un elemento casuale.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `item` | `Boolean` | no | `false` | Restituire un elemento casuale. |

Returns: `Array|Object`

Senza argomenti l'array viene mescolato sul posto (Fisher-Yates) e restituito. Con `item` impostato su `true`, viene restituito un elemento casuale e l'array non viene modificato.

Example: Mescolare e scegliere
```js
var deck = [1, 2, 3, 4, 5].random();
var winner = users.random(true);
```

### String.parseCSV([delimiter])

Type: `method`

Analizza un testo CSV e lo trasforma in un array di oggetti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `delimiter` | `String` | no | `','` | Il delimitatore delle colonne. |

Returns: `Object[]` Un oggetto per riga, con le chiavi `a`, `b`, `c`...

Ogni riga diventa un oggetto. Le colonne sono denominate con lettere: la prima è `a`, la seconda `b` e così via. I valori tra virgolette doppie possono contenere il delimitatore e degli a capo, e `""` tra virgolette è una virgoletta con escape. Tutti i valori restano stringhe, e una colonna vuota non ha alcuna chiave nell'oggetto. Una riga di intestazione non viene riconosciuta, quindi viene restituita come primo oggetto.

Example: Leggere un file CSV
```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`

Legge il sistema operativo, il browser e il tipo di dispositivo da una stringa user agent.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `structured` | `Boolean` | no | `false` | Restituire un oggetto invece di un testo. |

Returns: `String|Object` I nomi rilevati, oppure `{ os, browser, device }`.

Senza argomenti il metodo restituisce un breve testo con i nomi rilevati, come `Mac Chrome` o `iOS iPhone Mobile Safari`. Con `structured` impostato su `true` restituisce un oggetto `{ os, browser, device }`, dove `device` è `desktop`, `mobile`, `tablet` o `tv`. Una stringa vuota restituisce una stringa vuota.

Example: Rilevare il 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`

Analizza un testo `application/x-www-form-urlencoded` e lo trasforma in un oggetto.

Returns: `Object` Le chiavi e i valori analizzati.

Il testo ha l'aspetto di una query string: `key=value&key2=value2`. `+` diventa uno spazio e le sequenze `%xx` vengono decodificate. Tutti i valori restano stringhe; una chiave ripetuta unisce i suoi valori con una virgola. Le chiavi possono contenere solo lettere, cifre e `-`, `_`, `.`, `[`, `]`, e l'analisi si ferma al primo altro carattere in una chiave. Il numero di chiavi è limitato da `CONF.default_request_maxkeys` e la lunghezza di una chiave da `CONF.default_request_maxkey`.

Example: Analizzare il corpo di un form
```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`

Analizza un XML e lo trasforma in un oggetto piatto di percorsi e valori.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `replace` | `Boolean` | no | `false` | Sostituire con `_` i caratteri speciali nelle chiavi. |

Returns: `Object` L'oggetto piatto dei percorsi.

Ogni elemento con testo diventa una chiave composta dai nomi degli elementi uniti da punti, per esempio `book.title`. Un elemento ripetuto produce un array di valori. Gli attributi di un elemento vengono salvati come oggetto sotto il percorso seguito da `[]`. Le sezioni `CDATA` vengono lette come testo e i commenti vengono saltati. Con `replace` impostato su `true`, i caratteri `[`, `]`, `:`, `.` e `_` nelle chiavi vengono sostituiti con `_`.

Example: Leggere un feed XML
```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`

Analizza un HTML e lo trasforma in un albero di elementi che puoi cercare e modificare.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `trim` | `Boolean` | no | `false` | Rimuovere gli spazi esterni dal contenuto testuale. |

Returns: `HTMLElement` L'elemento radice del documento analizzato.

Il metodo usa il parser HTML integrato e restituisce l'elemento radice. Gli elementi hanno `tagName`, `attrs`, `children` e `parentNode`, e i metodi `find(selector)`, `closest(selector)`, `parent()`, `attr()`, `aclass()`, `rclass()`, `hclass()`, `tclass()`, `css()`, `append()`, `prepend()`, `remove()`, `text()` e `html([formatted])`. Con `trim` impostato su `true`, il testo all'interno degli elementi viene privato degli spazi esterni.

Example: Leggere e modificare 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`

Estrae blocchi delimitati da tag da un testo e ne restituisce il contenuto per nome.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `tags` | `Object` | yes |  | Il nome e il tag di apertura di ogni blocco. |

Returns: `Object` Il contenuto di ogni blocco trovato.

`tags` associa un nome a un tag di apertura, per esempio `{ js: '<script>', css: '<style>' }`. Per ogni nome viene restituito il contenuto tra il tag di apertura e il relativo tag di chiusura (i tag annidati dello stesso tipo vengono contati). Un tag mancante non produce alcuna chiave. Total.js lo usa per leggere la parte `<script total>` dei plugin e dei componenti `.html`.

Example: Dividere un file di componente
```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`

Analizza riga per riga l'output a colonne di un comando del terminale.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fields` | `Array` | no |  | Nomi delle intestazioni o espressioni regolari delle colonne. |
| `fn` | `Function` | yes |  | Chiamata come `fn(values, index, count, line)` per ogni riga. |
| `skip` | `Number` | no | `0` | Il numero di righe da saltare. |
| `take` | `Number` | no | `all` | Il numero di righe da leggere. |

Returns: `String` La stessa stringa.

Con `fields`, la prima riga non vuota (tra le prime tre) è l'intestazione. Ogni campo è il nome di un'intestazione (`String`) o una `RegExp` che trova la colonna nella riga di intestazione, e `fn` riceve i valori di quelle colonne per ogni riga successiva. Senza `fields`, ogni riga viene divisa in parole e `fn` riceve l'array delle parole. `fn(values, index, count, line)` riceve i valori, l'indice della riga analizzata, l'indice finale e il numero di riga. `skip` e `take` limitano le righe. Il metodo restituisce la stringa stessa.

Example: Leggere l'output di 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`

Analizza un testo nel formato di configurazione di Total.js e lo trasforma in un oggetto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Object` | no |  | Valori predefiniti copiati nel risultato. |
| `onerror` | `Function` | no |  | Chiamata come `onerror(err, line)` quando un valore `object` o `eval` fallisce. |

Returns: `Object` I valori analizzati.

Ogni riga è `key : value`, e le righe che iniziano con `#` o `//` vengono saltate. Il valore inizia due caratteri dopo il primo `:`, quindi scrivi uno spazio dopo i due punti. Un tipo tra parentesi dopo la chiave converte il valore: `(string)`, `(number)`, `(float)`, `(currency)`, `(boolean)`, `(array)` (separato da virgole), `(json)`, `(object)` o `(eval)` (valutato come JavaScript), `(date)`, `(env)` (una variabile d'ambiente), `(config)` (un'altra chiave di `CONF`) e `(random)` (una stringa casuale della lunghezza indicata). `def` fornisce i valori predefiniti. `onerror(err, line)` gestisce un valore che non può essere valutato; senza di essa il metodo solleva un'eccezione.

Example: Analizzare un testo di configurazione
```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`

Trasforma un testo come `5 minutes` in una data futura.

Returns: `Date` La data corrente più il tempo indicato.

Il testo viene letto come coppie di un numero e un'unità, separate da spazi, per esempio `1 day 12 hours`. Ogni coppia viene aggiunta alla data corrente con `Date.add()`, quindi funzionano le stesse unità (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`). Una coppia con il numero `0` viene ignorata.

Example: Scadenza di un cookie
```js
var expire = '7 days'.parseDateExpiration();
self.cookie('token', token, expire);

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

### String.parseUID()

Type: `method`

Legge le informazioni salvate in un identificatore creato da `UID()`.

Returns: `Object` `{ version, date, century, index, hash, valid }`.

Il risultato ha `version` (l'ultimo carattere dell'UID), `date` (quando è stato creato), `century`, `index` (il contatore), `hash` e `valid`. Per la versione casuale `r` (`CONF.default_uid = 'r'`) il risultato non ha data, e gli identificatori vengono validati con `String.isUID()`.

Example: Quando è stato creato un record
```js
var id = UID();
var info = id.parseUID();
console.log(info.date, info.index, info.valid);
```

### String.parseFloat2([def])

Type: `method`

Trova il primo numero decimale in un testo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Number` | no | `0` | Il valore restituito quando non viene trovato alcun numero. |

Returns: `Number` Il numero trovato.

A differenza di `String.parseFloat()`, il testo può contenere altri caratteri: viene usato il primo gruppo di cifre, punti e virgole, e le virgole diventano punti. Un `-` iniziale lo rende negativo. Senza un numero il metodo restituisce `def`.

Example: Prezzo da un'etichetta
```js
'Price: 12,50 EUR'.parseFloat2();	// 12.5
'no number'.parseFloat2(-1);		// -1
```

### String.isGUID()

Type: `method` · Since: `0.0.48`

Verifica se la stringa è un GUID (UUID).

Returns: `Boolean`

La stringa deve avere 36 caratteri nella forma `xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx`, dove `M` è una versione da 1 a 5. Sono accettate lettere maiuscole e minuscole.

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

### String.isJSONDate()

Type: `method`

Verifica se la stringa è una data nel formato JSON (ISO 8601 UTC).

Returns: `Boolean`

Il metodo verifica la forma del testo, come `2024-05-01T10:30:00.000Z`: la lunghezza, la `T`, i trattini e i due punti e la `Z` finale. Non verifica che la data esista.

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

### String.isNumber([decimal])

Type: `method`

Verifica se la stringa contiene solo cifre.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimal` | `Boolean` | no | `false` | Consentire un separatore decimale. |

Returns: `Boolean`

Con `decimal` impostato su `true`, è consentito anche un `.` o una `,`. Segni, spazi ed esponenti non sono accettati, e una stringa vuota restituisce `false`.

Example: Verificare l'input dell'utente
```js
'12345'.isNumber();		// true
'12.5'.isNumber();		// false
'12.5'.isNumber(true);	// true
'-1'.isNumber();		// false
```

### String.isBoolean()

Type: `method`

Verifica se la stringa è `true` o `false`.

Returns: `Boolean`

Il confronto non distingue tra maiuscole e minuscole. Altri valori come `1` o `on` restituiscono `false`; questi li legge `String.parseBoolean()`.

Example: Verificare un valore della query
```js
'TRUE'.isBoolean();	// true
'on'.isBoolean();	// false
```

### String.isZIP()

Type: `method`

Verifica se la stringa sembra un codice postale (CAP).

Returns: `Boolean`

La stringa viene verificata con `DEF.validators.zip`, per impostazione predefinita da 3 a 20 lettere, cifre, spazi o trattini. Modifica `DEF.validators.zip` per usare una tua regola.

Example: Validare un codice postale
```js
'821 08'.isZIP();	// true
'12'.isZIP();		// false
```

### String.isXSS()

Type: `method`

Verifica se la stringa contiene un tag HTML.

Returns: `Boolean`

Il test è semplice: restituisce `true` quando il testo contiene `<` seguito più avanti da `>`. Usalo per rifiutare l'HTML nei campi di testo semplice.

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

### String.isSQLInjection()

Type: `method`

Verifica se la stringa contiene un testo tra virgolette o una parola chiave SQL.

Returns: `Boolean`

Il metodo restituisce `true` per un testo tra virgolette singole o per le parole maiuscole `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `EXECUTE`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` e `UNION`. È un controllo approssimativo; usa comunque i parametri nelle tue query.

Example: Verificare una frase di ricerca
```js
'shoes'.isSQLInjection();					// false
"1; DROP TABLE users".isSQLInjection();	// true
```

### String.isBase64([data])

Type: `method`

Verifica se la stringa è codificata in base64.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Boolean` | no | `false` | Accettare un prefisso data URI. |

Returns: `Boolean`

La lunghezza deve essere divisibile per 4 e il testo deve contenere solo caratteri base64. Con `data` impostato su `true`, viene accettato un data URI come `data:image/png;base64,...` e viene verificata solo la lunghezza della parte codificata.

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

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

Type: `method`

Scrive dati base64 in un file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | Il percorso del file. |
| `callback` | `Function` | no |  | Chiamata come `callback(err)` quando il file è stato scritto. |

Returns: `String` La stessa stringa.

Un prefisso data URI (tutto fino alla prima virgola) viene rimosso, e il resto viene decodificato e scritto con `fs.writeFile()`. Il metodo restituisce la stringa stessa; il risultato della scrittura arriva a `callback(err)`.

Example: Salvare un'immagine caricata
```js
model.photo.base64ToFile(PATH.public('photos/' + UID() + '.png'), function(err) {
	err && console.log(err);
});
```

### String.base64ToBuffer()

Type: `method`

Decodifica dati base64 in un `Buffer`.

Returns: `Buffer` I dati decodificati.

Un prefisso data URI (tutto fino alla prima virgola) viene rimosso prima della decodifica.

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

### String.base64ContentType()

Type: `method`

Restituisce il content type di un data URI.

Returns: `String` Il content type, per esempio `image/png`.

Viene restituito il testo tra `data:` e il primo `;`. Una stringa senza `;` restituisce una stringa vuota.

Example: Verificare il tipo di un 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`

Calcola il checksum CRC32 della stringa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `unsigned` | `Boolean` | no | `false` | Restituire un numero senza segno. |

Returns: `Number` Il checksum.

Il risultato è un numero a 32 bit con segno, oppure senza segno quando `unsigned` è `true`. `String.hash('crc32')` e `String.hash('crc32unsigned')` danno gli stessi risultati.

Example: Checksum di un testo
```js
var checksum = 'Hello world'.crc32(true);
var key = checksum.toString(36);
```

### String.sha1([salt])

Type: `method`

Crea un hash SHA-1 della stringa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `salt` | `String` | no |  | Testo aggiunto prima del calcolo dell'hash. |

Returns: `String` L'hash in esadecimale.

Il `salt` viene aggiunto alla stringa prima del calcolo dell'hash.

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

### String.sha512([salt])

Type: `method`

Crea un hash SHA-512 della stringa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `salt` | `String` | no |  | Testo aggiunto prima del calcolo dell'hash. |

Returns: `String` L'hash in esadecimale.

Il `salt` viene aggiunto alla stringa prima del calcolo dell'hash.

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

### String.makeid()

Type: `method`

Crea un id breve dalla stringa.

Returns: `String` L'id.

L'id è un hash veloce senza segno della stringa scritto in base 36. La stessa stringa produce sempre lo stesso id. Non è un hash crittografico.

Example: Id per una chiave di cache
```js
var key = ('products_' + JSON.stringify(query)).makeid();
```

### String.sign([key])

Type: `method` · Since: `0.0.81`

Aggiunge un checksum veloce alla stringa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | no |  | Un segreto mescolato nel checksum. |

Returns: `String` La stringa con il checksum.

Il risultato è la stringa, un trattino e un hash in base 36 della stringa con `key`. Per verificare un valore, firma di nuovo la parte prima dell'ultimo trattino e confronta. È un checksum veloce, non una firma crittografica.

Example: Firmare e verificare un valore
```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`

Protegge un identificatore con un checksum.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | no | `CONF.secret` | Il segreto. |

Returns: `String` L'identificatore protetto.

Il risultato è `x`, un checksum e `x` seguiti dal valore originale, quindi il valore resta leggibile ma non può essere modificato senza la chiave. Il checksum usa `key` (predefinito `CONF.secret`) e `CONF.secret_uid`. Rileggilo con `String.decrypt_uid()`. La stessa funzione per i numeri è `U.encrypt_uid(value, [key])`.

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

### String.decrypt_uid([key])

Type: `method`

Legge un identificatore protetto con `String.encrypt_uid()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | no | `CONF.secret` | Il segreto usato per `encrypt_uid()`. |

Returns: `String|Number` Il valore originale, oppure `null` quando il checksum è errato.

Il checksum viene ricreato con `key` (predefinito `CONF.secret`). Quando corrisponde, viene restituito il valore originale, altrimenti `null`. Un valore creato da un numero viene restituito come numero.

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

### String.toName()

Type: `method`

Pulisce il nome di una persona: rimuove gli altri caratteri e rende maiuscola l'iniziale di ogni parola.

Returns: `String` Il nome pulito.

Cifre e punteggiatura ASCII vengono rimosse, gli spazi vengono mantenuti e la prima lettera di ogni parola diventa maiuscola. Le lettere con segni diacritici vengono mantenute. Gli spazi finali vengono eliminati, ma quelli iniziali e ripetuti no, quindi rimuovi prima gli spazi esterni dall'input.

Example: Pulire un nome da un form
```js
'peter sirka2'.toName();	// Peter Sirka
"john o'neil".toName();	// John Oneil
```

### String.toUnicode()

Type: `method`

Esegue l'escape dei caratteri al di fuori dell'ASCII stampabile come `\uXXXX`.

Returns: `String` La stringa con escape.

I caratteri con un codice inferiore a 32 o superiore a 126 vengono scritti come `\u` e quattro cifre esadecimali. `String.fromUnicode()` esegue l'operazione inversa.

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

### String.fromUnicode()

Type: `method`

Ritrasforma gli escape `\uXXXX` in caratteri.

Returns: `String` La stringa senza escape.

Ogni `\u` seguito da quattro cifre esadecimali viene sostituito con il carattere. È l'operazione inversa di `String.toUnicode()`.

Example: Rimuovere l'escape da un testo
```js
'\\u017dlt\\u00fd'.fromUnicode(); // Žltý
```

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

Type: `method`

Verifica se la stringa termina con un testo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | yes |  | Il testo da cercare. |
| `ignoreCase` | `Boolean|Number` | no | `false` | `true` per ignorare maiuscole e minuscole, oppure un offset dalla fine. |

Returns: `Boolean`

Total.js sostituisce il metodo nativo. Con `ignoreCase` impostato su `true`, maiuscole e minuscole vengono ignorate. Un numero al posto di `ignoreCase` verifica il testo che si trova quel numero di caratteri prima della fine.

Example: Verificare l'estensione di un file
```js
'Photo.JPG'.endsWith('.jpg', true);	// true
'Photo.JPG'.endsWith('.jpg');		// false
```

### String.replacer(find, text)

Type: `method`

Sostituisce la prima occorrenza di un testo, senza espressioni regolari.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `find` | `String` | yes |  | Il testo da sostituire. |
| `text` | `String` | yes |  | Il nuovo testo. |

Returns: `String` La nuova stringa.

`find` è testo semplice, quindi caratteri come `$` o `.` non hanno alcun significato speciale né in esso né in `text`. Quando `find` non viene trovato, la stringa viene restituita invariata.

Example: Inserire un prezzo in un template
```js
'Total: {price}'.replacer('{price}', '$ 25'); // Total: $ 25
```

### String.insert(index, value)

Type: `method`

Inserisce un valore in una posizione della stringa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `index` | `Number` | yes |  | La posizione. |
| `value` | `Object` | yes |  | Il valore da inserire. |

Returns: `String` La nuova stringa.

Il valore viene convertito in stringa con `toString()`.

Example: Formattare un codice
```js
'ABCDEF'.insert(3, '-'); // ABC-DEF
```

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

Type: `method`

Aggiunge un carattere all'inizio della stringa un certo numero di volte.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | Quanti caratteri aggiungere. |
| `char` | `String` | no | `' '` | Il carattere. |

Returns: `String` La stringa indentata.

A differenza di `String.padLeft()`, i caratteri vengono sempre aggiunti, qualunque sia la lunghezza della stringa.

Example: Indentare una riga
```js
'item'.indent(2, '\t'); // \t\titem
'item'.indent(4);		// '    item'
```

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

Type: `method`

Sceglie la forma di una parola in base al numero nella stringa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `zero` | `String` | yes |  | La forma per 0, oppure tutte le forme separate da virgole. |
| `one` | `String` | no |  | La forma per 1. |
| `few` | `String` | no |  | La forma da 2 a 4. |
| `other` | `String` | no |  | La forma per gli altri numeri. |

Returns: `String` La forma scelta.

La stringa viene letta con `String.parseInt()` e passata a `Number.pluralize()`, quindi le regole e il segnaposto `#` sono gli stessi.

Example: Conteggio da una query
```js
var count = self.query.count || '0';
count.pluralize('no items', '# item', '# items', '# items');
```

### String.env()

Type: `method`

Sostituisce i segnaposto `[key]` con i valori di configurazione.

Returns: `String` La stringa con i valori.

Ogni `[key]` (lettere, cifre e `_`) viene sostituito con `CONF[key]`; una chiave mancante produce una stringa vuota.

Example: Costruire un URL dalla configurazione
```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`

Trova blocchi in una stringa e passa ciascuno a una callback.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `beg` | `String` | yes |  | Il delimitatore iniziale, oppure il separatore quando `end` manca. |
| `end` | `String` | no |  | Il delimitatore finale. |
| `callback` | `Function` | yes |  | Chiamata come `callback(value, index)`; restituisci `false` per fermarti. |
| `skip` | `Number` | no | `0` | Il numero di blocchi da saltare. |

Returns: `undefined`

Con `beg` ed `end`, viene passato ogni blocco che inizia con `beg` e termina con `end`, delimitatori inclusi. Senza `end`, la stringa viene divisa dopo ogni `beg`, e ogni parte termina con `beg`. `callback(value, index)` può restituire `false` per fermarsi. `skip` salta i primi blocchi.

Example: Leggere elementi da un 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`

Arrotonda il numero a un certo numero di decimali e restituisce un numero.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimals` | `Number` | yes |  | Il numero di decimali. |

Returns: `Number` Il numero arrotondato.

Equivale a `+number.toFixed(decimals)`: a differenza di `toFixed()`, il risultato è un numero, non una stringa.

Example: Arrotondare un prezzo
```js
(12.3456).fixed(2); // 12.35
```

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

Type: `method`

Formatta il numero con un formattatore di valuta da `DEF.currencies`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `currency` | `String` | no | `'default'` | La chiave in `DEF.currencies`. |
| `a` | `Object` | no |  | Passato al formattatore, come `b` e `c`. |

Returns: `String` Il prezzo formattato.

`DEF.currencies` è vuoto per impostazione predefinita; aggiungi una funzione `function(value, a, b, c)` per ogni codice di valuta che ti serve, e `default` per le chiamate senza codice. Gli argomenti aggiuntivi le vengono passati. Senza un formattatore il numero viene formattato con `Number.format(2)`.

Example: Registrare e usare valute
```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`

Converte il numero in esadecimale maiuscolo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | no |  | La lunghezza minima. |

Returns: `String` Il valore esadecimale.

Il risultato viene completato con zeri iniziali fino a `length` caratteri.

Example: Componente di un colore
```js
(255).hex();	// FF
(10).hex(2);	// 0A
```

### Number.parseDate([plus])

Type: `method`

Crea una data da un timestamp in millisecondi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `plus` | `Number` | no | `0` | Millisecondi da aggiungere. |

Returns: `Date` La data.

Al numero vengono aggiunti `plus` millisecondi prima di creare la data.

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

### Number.toRad()

Type: `method`

Converte i gradi in radianti.

Returns: `Number` L'angolo in radianti.

Definito solo quando `Number.prototype.toRad` non esiste ancora.

Example: Distanza tra due punti GPS
```js
var dlat = (lat2 - lat1).toRad();
var dlon = (lon2 - lon1).toRad();
```

### Date.parseDate()

Type: `method`

Restituisce la data stessa.

Returns: `Date` La stessa data.

Ti permette di chiamare `parseDate()` su un valore che può essere una stringa, un numero o una data, senza verificarne prima il tipo.

Example: Valore di tipo sconosciuto
```js
var value = model.date; // String, Number or Date
var date = value.parseDate();
```
