---
title: Prototipi
project: Total.js V5
version: 0.0.20
section: guides
language: it
license: MIT
url: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/prototypes/
updated: 2026-11-16T15:32:42.496Z
---

# Prototipi

> Metodi che Total.js aggiunge a String, Number, Date e Array: formattazione, parsing, validazione, hashing, date e helper per gli array.

Total.js 5 aggiunge una serie di metodi ai prototipi integrati di JavaScript: `String`, `Number`, `Date` e `Array`. Sono disponibili in ogni file dell'applicazione (controller, azioni, schemi, definizioni, viste) non appena il framework è caricato; non devi importare nulla.

```js
var title = 'Hello World!';
title.slug();                     // hello-world
'{0} items'.format(5);            // 5 items
(1234.5).format(2);               // 1 234.50
new Date().add('1 day').format('yyyy-MM-dd');
users.findItem('id', 5);
```

L'elenco completo con ogni argomento è nel riferimento [Prototipi](../../reference/prototypes/). Questa guida mostra i gruppi e i metodi che userai di più.

## Stringhe: template e testo

`format()` riempie i segnaposto numerati e `args()` quelli con nome. `args()` può codificare i valori per HTML, JSON o URL:

```js
'Hello {0}, you have {1} messages.'.format('Peter', 5);

var tpl = '<a href="/users/{id}/">{name}</a>';
tpl.args({ id: 10, name: '<Peter>' }, 'html');
// <a href="/users/10/">&lt;Peter&gt;</a>
```

Per il testo degli utenti e per gli URL:

```js
'Čaute, svet!'.slug();          // caute-svet
'<b>Hi</b>'.encode();           // &lt;b&gt;Hi&lt;/b&gt;
'&lt;b&gt;'.decode();           // <b>
'<p>Hi</p>'.removeTags();       // Hi
'A long description'.max(10);   // A long ...
'hello world'.capitalize();     // Hello World
'Čučoriedka'.toASCII();         // Cucoriedka
```

`toKeywords()` e `toSearch()` preparano il testo per una semplice ricerca full-text: lo convertono in minuscolo, rimuovono i segni diacritici e i simboli, e rendono il confronto tollerante (`y` e `i` sono equivalenti).

## Stringhe: parsing

I metodi `parse*` non generano eccezioni per input non validi: restituiscono invece un valore predefinito, `undefined` o una data non valida. Solo `parseConfig()` genera un'eccezione per un valore che non può essere valutato quando non passi `onerr`. Questo li rende sicuri per query string e body delle richieste.

```js
'10'.parseInt();                 // 10
'abc'.parseInt(1);               // 1 (the default)
'1,5'.parseFloat();              // 1.5
'on'.parseBoolean();             // true
'{"a":1}'.parseJSON();           // { a: 1 }, or undefined for bad JSON
'2024-05-01 12:30'.parseDate();  // a Date in UTC
'01/05/2024'.parseDate('dd/MM/yyyy');
'5 minutes'.parseDateExpiration(); // now + 5 minutes
```

I formati di testo strutturati hanno i propri parser:

```js
'q=total&page=2'.parseEncoded();       // { q: 'total', page: '2' }
'PORT=8000\nNAME="App"'.parseEnv();    // { PORT: '8000', NAME: 'App' }
'count (number) : 10'.parseConfig();   // { count: 10 }
'a,b\n1,2'.parseCSV();                 // [{ a: 'a', b: 'b' }, { a: '1', b: '2' }]
req.headers['user-agent'].parseUA();   // Windows Chrome
```

`parseContext()` legge un testo composto da blocchi. Ogni blocco ha righe di intestazione tra due righe di almeno 20 trattini e un corpo dopo di esse; il risultato è un array di oggetti con le chiavi dell'intestazione (in minuscolo) e `body`:

```js
var text = PATH.root('prompts.txt');
var blocks = Total.Fs.readFileSync(text, 'utf8').parseContext();
// [{ name: 'welcome', type: 'prompt', body: '...' }, ...]
```

`parseCSV()` assegna alle colonne delle lettere (`a`, `b`, `c`, ...), quindi un file con una riga di intestazione restituisce l'intestazione come primo oggetto. Leggi l'intestazione, poi associa le lettere ai tuoi nomi:

```js
var rows = text.parseCSV(';');
var header = rows.shift();
var users = rows.map(row => ({ name: row.a, email: row.b }));
```

## Stringhe: validazione

I metodi `is*` restituiscono un booleano. `isEmail()`, `isPhone()`, `isURL()`, `isXSS()` e `isSQLInjection()` usano espressioni regolari salvate in `DEF.validators`, quindi puoi sostituirne una all'avvio quando le tue regole sono diverse:

```js
'info@example.com'.isEmail();     // true
'+421903123456'.isPhone();        // true
'https://totaljs.com'.isURL();    // true
UID().isUID();                    // true (the checksum is checked too)
'123'.isNumber();                 // true
'<script>'.isXSS();               // true

// /definitions/validators.js
DEF.validators.phone = /^\+?[0-9\s]{6,20}$/;
```

## Stringhe: hashing e cifratura

```js
'text'.hash();               // a fast 32-bit number, for cache keys
'text'.hash('sha256');       // the same as 'text'.sha256()
'text'.md5();
'password'.sha512(CONF.secret);

var link = '123'.sign('key');    // 123-nzo165
link.sign('key', true);          // 123, or null when the text was changed

var secret = 'user@example.com'.encrypt('key');
secret.decrypt('key');           // user@example.com

var token = '123'.encrypt_uid(); // a short token for public URLs
token.decrypt_uid();             // 123
```

`encrypt()`, `decrypt()`, `encrypt_uid()` e `decrypt_uid()` usano la chiave di configurazione `secret` quando non passi un segreto, così tutte le istanze di un'applicazione con la stessa configurazione possono leggere i valori l'una dell'altra.

## Numeri

```js
(1234567.891).format(2);              // 1 234 567.89
(1234.5).format(2, ',', '.');         // 1,234.50
(1.005).round(2);                     // 1.01
(100).VAT(20);                        // 120
(100).discount(15);                   // 85
(5).padLeft(3);                       // 005
(1536000).filesize();                 // 1.46 MB
(3).pluralize('no files', '# file', '# files', '# files'); // 3 files
(5).between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }); // medium
```

`format()` tronca i decimali in eccesso invece di arrotondarli: arrotonda prima con `round()` quando conta, per esempio per i prezzi. `currency()` formatta un importo con una funzione che registri in `DEF.currencies`.

## Date

L'applicazione gira in UTC, a meno che la chiave di configurazione `$timezone` non dica altrimenti, quindi le date vengono formattate in UTC per impostazione predefinita.

```js
var now = new Date();
now.add('1 day');                    // a new Date, now is not changed
now.add('-30 minutes');
now.format('yyyy-MM-dd HH:mm');      // 2024-05-01 12:30
now.format('dddd, d. MMMM yyyy');    // Wednesday, 1. May 2024
now.format();                        // ISO string in UTC
now.extend('08:00');                 // the same day at 08:00
now.diff(created, 'days');           // days between created and now
now.setTimeZone('America/New_York').format('HH:mm'); // the time in New York
```

## Array

I metodi di ricerca accettano una funzione, un nome di proprietà con un valore, oppure un singolo valore:

```js
var users = [{ id: 1, name: 'Peter', role: 'admin' }, { id: 2, name: 'Anna', role: 'user' }];

users.findItem('id', 2);              // { id: 2, ... } or null
users.findAll('role', 'admin');       // an array
users.findIndex(u => u.name === 'Anna'); // 1
users.findValue('id', 1, 'name');     // Peter
users = users.remove('id', 1);        // a new array without the item

users.quicksort('name');              // in place, by name
users.quicksort('role,name_desc');    // several columns
users.group('role');                  // [{ name: 'admin', items: [...] }, ...]
all.skip(20).take(10);                // paging
```

`remove()`, `findAll()`, `take()` e `skip()` restituiscono nuovi array; `quicksort()` e `random()` modificano l'array stesso.

Per il lavoro asincrono sugli elementi, `wait()` chiama una funzione per ogni elemento e attende `next()`. Il terzo argomento elabora più elementi contemporaneamente:

```js
files.wait(function(file, next) {
	FUNC.process(file, next);
}, function() {
	console.log('All files are processed');
}, 3);
```

`async()` esegue in sequenza un array di funzioni e `limit()` elabora un array a blocchi, comodo per inserire molte righe a lotti.
