---
title: String
project: jComponent V19
version: 19.194
section: reference
language: it
license: MIT
url: https://totaljs.es/docs/it/jcomponent-v19/19-194/reference/string/
updated: 2026-11-18T13:58:29.465Z
---

# String

> Metodi che jComponent aggiunge a String.prototype per formattare, analizzare, convalidare e convertire il testo.

jComponent aggiunge questi metodi a `String.prototype`, quindi sono disponibili su ogni stringa non appena la libreria viene caricata. Numeri e date hanno i propri helper nelle pagine [Number](../number/) e [Date](../date/), e [Template con Tangular](../../guides/tangular/) spiega la sintassi dei template usata da `render()`.

## API

### str.arg(obj, [encode], [def])

Type: `method`

Sostituisce i segnaposto `{key}` e `{{ key }}` con i valori letti da un oggetto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | L'origine dei valori. |
| `encode` | `Boolean, String or Function` | no |  | Come vengono codificati i valori. |
| `def` | `String` | no |  | Il testo usato per i segnaposto senza valore. |

Returns: `String` Il testo con i valori applicati.

Una chiave può essere un path annidato come `{user.name}`. Un segnaposto senza valore resta nel testo, a meno che non sia impostato `def`. `args()` è un altro nome dello stesso metodo.

L'argomento `encode` cambia il modo in cui vengono scritti i valori:

| Valore | Risultato |
| --- | --- |
| `true` | Il valore viene codificato per URL. |
| `'escape'` | Il valore viene codificato in HTML. Ogni segnaposto deve avere un valore. |
| `'json'` | Il valore viene scritto come JSON. Ogni segnaposto deve avere un valore. |
| Funzione | `function(value, key)` restituisce il testo da scrivere. |

Example: Segnaposto
```js
'Hello {name}, {age}'.arg({ name: 'Ann', age: 30 }); // "Hello Ann, 30"
'Hello {{ user.name }}'.arg({ user: { name: 'Ann' } }); // "Hello Ann"
'Hello {name}'.arg({}); // "Hello {name}"
'Hello {name}'.arg({}, undefined, 'guest'); // "Hello guest"
```

Example: Codifica
```js
'/search?q={q}'.arg({ q: 'a b&c' }, true); // "/search?q=a%20b%26c"
'<b>{name}</b>'.arg({ name: '<i>' }, 'escape'); // "<b>&lt;i&gt;</b>"
'data={value}'.arg({ value: { id: 1 } }, 'json'); // "data={\"id\":1}"
'{price}'.arg({ price: 2 }, (value, key) => key + '=' + (value * 2)); // "price=4"
```

### str.COMPILABLE()

Type: `method`

Controlla se una stringa HTML contiene un attributo di associazione o una dichiarazione di componente.

Returns: `Boolean` `true` quando il testo ne contiene uno.

Il metodo cerca gli attributi `data--`, `data---`, `data-import`, `-bind` e `bind`, oltre a una chiamata `COMPONENT(`.

Example: Controlla un template
```js
'<div data-bind="user.name"></div>'.COMPILABLE(); // true
'<div>Hello</div>'.COMPILABLE(); // false
```

### str.encode()

Type: `method`

Codifica i caratteri `<`, `>`, `&` e `"` come entità HTML.

Returns: `String` Il testo codificato.

Example: Codifica un testo
```js
'<a href="#">Tom & Ann</a>'.encode(); // "&lt;a href=&quot;#&quot;&gt;Tom &amp; Ann&lt;/a&gt;"
```

### str.env()

Type: `method`

Sostituisce `[key]` con un valore di `ENV()` e `[.path]` con un valore del modello.

Returns: `String` Il testo con i valori applicati.

Una chiave senza valore resta nel testo.

Example: Leggi i valori dell'ambiente
```js
ENV('site', 'Docs');
SET('common.title', 'Hello');
'[site] page'.env(); // "Docs page"
'[.common.title] page'.env(); // "Hello page"
'[missing] page'.env(); // "[missing] page"
```

### str.flags([path], [value], [type])

Type: `method`

Rimuove le parole `@flag` dal testo ed emette un evento per ciascuna.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | no |  | Il primo argomento dell'evento. |
| `value` | `Object` | no |  | Il secondo argomento dell'evento. |
| `type` | `Number or String` | no |  | Il terzo argomento dell'evento. |

Returns: `String` Il testo senza i flag.

Ogni flag emette l'evento `@flag name` con gli argomenti `path`, `value` e `type`. La guida [Flag e modificatori di path](../../guides/flags/) spiega come si usano i flag.

Example: Rimuovi i flag
```js
ON('@flag hidden', function(path, value, type) {
	console.log('flag', path, value, type);
});

var path = 'user.name @hidden'.flags('user.name', 'Ann', 1);
console.log(path);
```

### str.format(a, [b], [c], ...)

Type: `method`

Sostituisce i segnaposto posizionali `{0}`, `{1}` e così via con gli argomenti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `a` | `Object` | yes |  | Il valore per `{0}`. Ogni argomento successivo riempie la posizione seguente. |

Returns: `String` Il testo formattato.

Un argomento mancante o `null` scrive un testo vuoto. Un array viene unito senza separatore.

Example: Valori posizionali
```js
'{0} and {1}'.format('Ann', 'Bob'); // "Ann and Bob"
'{0}-{1}-{2}'.format('a', null, ['x', 'y']); // "a--xy"
```

### str.isEmail()

Type: `method`

Controlla se il testo è un indirizzo email.

Returns: `Boolean` `true` per un indirizzo valido.

Example: Convalida un indirizzo
```js
'ann@example.com'.isEmail(); // true
'ann@example'.isEmail(); // false
```

### str.isJSONDate()

Type: `method`

Controlla se il testo ha la forma di una data serializzata in JSON.

Returns: `Boolean` `true` quando il testo ha la forma `yyyy-MM-ddTHH:mm:ss.sssZ`.

Il metodo controlla la lunghezza, le posizioni dei separatori e la `Z` finale. Non convalida i valori.

Example: Rileva una data JSON
```js
'2026-11-18T10:20:30.000Z'.isJSONDate(); // true
'2026-11-18'.isJSONDate(); // false
```

### str.isPhone()

Type: `method`

Controlla se il testo è un numero di telefono.

Returns: `Boolean` `true` per un numero valido.

Il numero ha un `+` facoltativo, un gruppo di tre cifre che può stare tra parentesi, un gruppo di tre cifre e un gruppo da quattro a otto cifre. I gruppi possono essere separati da un singolo spazio, `-` o `.`.

Example: Convalida un numero
```js
'+421903123456'.isPhone(); // true
'123-456-7890'.isPhone(); // true
'12345'.isPhone(); // false
```

### str.isURL()

Type: `method`

Controlla se il testo è un indirizzo `http` o `https`.

Returns: `Boolean` `true` per un indirizzo valido.

Example: Convalida un indirizzo
```js
'https://www.totaljs.com'.isURL(); // true
'ftp://example.com/file'.isURL(); // false
'totaljs.com'.isURL(); // false
```

### str.padLeft(length, [char])

Type: `method`

Aggiunge un carattere a sinistra finché il testo non raggiunge una certa lunghezza.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | La lunghezza finale. |
| `char` | `String` | no | `' '` | Il carattere da aggiungere. |

Returns: `String` Il testo riempito.

Un testo già abbastanza lungo viene restituito senza modifiche.

Example: Riempi a sinistra
```js
'5'.padLeft(3, '0'); // "005"
'5'.padLeft(3); // "  5"
'hello'.padLeft(3, '0'); // "hello"
```

### str.padRight(length, [char])

Type: `method`

Aggiunge un carattere a destra finché il testo non raggiunge una certa lunghezza.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | La lunghezza finale. |
| `char` | `String` | no | `' '` | Il carattere da aggiungere. |

Returns: `String` Il testo riempito.

Un testo già abbastanza lungo viene restituito senza modifiche.

Example: Riempi a destra
```js
'5'.padRight(3, '-'); // "5--"
```

### str.parseConfig([def], [callback])

Type: `method`

Analizza un testo `key:value;key:value` e lo converte in un oggetto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `String, Object or Function` | no |  | I valori predefiniti come testo di configurazione o come oggetto. Una funzione viene usata come `callback`. |
| `callback` | `Function` | no |  | `function(key, value)` viene chiamata per ogni coppia analizzata. |

Returns: `Object` La configurazione analizzata.

I valori `true` e `false` diventano booleani e i valori numerici diventano numeri. Usa `\:` e `\;` per scrivere questi caratteri in un valore; i due punti di un indirizzo `http://`, `https://`, `ws://` o `wss://` non richiedono l'escape. Chiavi e valori passano attraverso [env()](#env). Una coppia con più di due punti senza escape viene saltata.

Quando `def` è un oggetto, i valori vengono scritti in quell'oggetto e viene restituito lo stesso oggetto.

Example: Analizza una configurazione
```js
'title:Hello;limit:10;visible:true'.parseConfig(); // {"title":"Hello","limit":10,"visible":true}
'url:https://www.totaljs.com;size:2'.parseConfig(); // {"url":"https://www.totaljs.com","size":2}
```

Example: Valori predefiniti e un callback
```js
'limit:10'.parseConfig('limit:5;page:1'); // {"limit":10,"page":1}

var keys = [];
'a:1;b:2'.parseConfig((key, value) => keys.push(key + '=' + value));
keys; // ["a=1","b=2"]
```

### str.parseDate([format])

Type: `method`

Converte il testo in un `Date`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `format` | `String` | no |  | Il layout del testo. |

Returns: `Date` La data analizzata, oppure `null` per un testo vuoto.

Senza `format`, il metodo legge `yyyy-MM-dd` e `dd.MM.yyyy`, eventualmente seguiti da un orario nella forma `HH:mm` o `HH:mm:ss`, separato da uno spazio o da `T`. Un testo che termina con `Z` viene letto come data UTC. Qualsiasi altro testo passa al costruttore `Date`. Un orario da solo usa la data corrente.

Con `format`, le cifre del testo vengono lette in base alla posizione, quindi ogni valore deve avere la larghezza del proprio token. I token supportati sono `yyyy`, `yy`, `MM`, `dd`, `HH`, `mm` e `ss`. Un anno a due cifre viene sommato a 2000. Il formato deve contenere il giorno.

Example: Rilevamento automatico
```js
'2026-11-18 14:05:09'.parseDate().format('dd.MM.yyyy HH:mm:ss'); // "18.11.2026 14:05:09"
'18.11.2026'.parseDate().format('yyyy-MM-dd'); // "2026-11-18"
'2026-11-18T13:05:09.000Z'.parseDate().getTime() === Date.UTC(2026, 10, 18, 13, 5, 9); // true
''.parseDate(); // null
```

Example: Un layout personalizzato
```js
'18/11/2026'.parseDate('dd/MM/yyyy').format('yyyy-MM-dd'); // "2026-11-18"
'20261118'.parseDate('yyyyMMdd').format('yyyy-MM-dd'); // "2026-11-18"
'18.11.26 14:05'.parseDate('dd.MM.yy HH:mm').format('yyyy-MM-dd HH:mm'); // "2026-11-18 14:05"
```

### str.parseEncoded()

Type: `method`

Analizza una stringa di query di un URL e la converte in un oggetto.

Returns: `Object` I valori analizzati.

Tutto ciò che precede `?` e tutto ciò che segue `#` viene ignorato. Chiavi e valori vengono decodificati con `decodeURIComponent()` e tutti i valori restano stringhe.

Example: Leggi una stringa di query
```js
'name=Ann&city=New%20York'.parseEncoded(); // {"name":"Ann","city":"New York"}
'/products/?page=2&sort=asc#top'.parseEncoded(); // {"page":"2","sort":"asc"}
```

### str.parseExpire()

Type: `method`

Converte una durata come `5 minutes` in millisecondi.

Returns: `Number` La durata in millisecondi.

Il testo contiene un numero, uno spazio e un'unità. Un'unità sconosciuta restituisce `0`, così come un testo che non inizia con un numero.

| Unità | Nomi accettati |
| --- | --- |
| Secondi | `seconds`, `second`, `sec`, `ss`, `s` |
| Minuti | `minutes`, `minute`, `min`, `mm`, `m` |
| Ore | `hours`, `hour`, `HH`, `hh`, `h`, `H` |
| Giorni | `days`, `day`, `DD`, `dd`, `d` |
| Settimane | `weeks`, `week`, `W`, `w` |
| Mesi (28 giorni) | `months`, `month`, `MM`, `M` |
| Anni (365 giorni) | `years`, `year`, `yyyy`, `yy`, `y` |

Example: Durate
```js
'30 seconds'.parseExpire(); // 30000
'5 minutes'.parseExpire(); // 300000
'1 day'.parseExpire(); // 86400000
'1 month'.parseExpire(); // 2419200000
'none'.parseExpire(); // 0
```

### str.parseFloat([def])

Type: `method`

Legge il primo numero decimale dal testo.

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

Returns: `Number` Il numero analizzato.

Il separatore decimale può essere un punto o una virgola. Un numero che li contiene entrambi, come `1,234.5`, non è valido e restituisce il valore predefinito.

Example: Leggi un numero decimale
```js
'12.5'.parseFloat(); // 12.5
'12,5'.parseFloat(); // 12.5
'-3.25 kg'.parseFloat(); // -3.25
'abc'.parseFloat(1.5); // 1.5
```

### str.parseInt([def])

Type: `method`

Legge il primo numero intero dal testo.

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

Returns: `Number` Il numero analizzato.

Example: Leggi un numero intero
```js
'123abc'.parseInt(); // 123
' -42 '.parseInt(); // -42
'a12b3'.parseInt(); // 12
'abc'.parseInt(7); // 7
```

### str.parseSource([type])

Type: `method`

Analizza un elenco `id|name|icon` e lo converte in un array di oggetti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `Number or String` | no |  | Usa `Number` o `'number'` per convertire gli identificatori in numeri. |

Returns: `Array` Oggetti con i campi `id`, `name` e `icon`.

Gli elementi sono separati da virgole. Il nome predefinito è l'identificatore e l'icona predefinita è un testo vuoto.

Example: Analizza un elenco
```js
'1|One|ti ti-star,2|Two'.parseSource(); // [{"id":"1","name":"One","icon":"ti ti-star"},{"id":"2","name":"Two","icon":""}]
'1|One,2'.parseSource(Number); // [{"id":1,"name":"One","icon":""},{"id":2,"name":"2","icon":""}]
```

### str.removeTags()

Type: `method`

Rimuove i tag HTML dal testo.

Returns: `String` Il testo senza tag.

Tutto ciò che va da un `<` al `>` successivo viene trattato come un tag.

Example: Rimuovi l'HTML
```js
'<p>Hello <b>world</b></p>'.removeTags(); // "Hello world"
```

### str.render(model, [repository])

Type: `method`

Compila il testo come template Tangular e ne esegue il rendering.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `model` | `Object` | yes |  | I dati del template. |
| `repository` | `Object` | no |  | Dati aggiuntivi, disponibili nel template come `$`. |

Returns: `String` L'output renderizzato.

La guida [Template con Tangular](../../guides/tangular/) descrive la sintassi.

Example: Esegui il rendering di un template
```js
'Hello {{ name }}'.render({ name: '<Ann>' }); // "Hello &lt;Ann&gt;"
'{{ $.title }}: {{ name }}'.render({ name: 'Ann' }, { title: 'User' }); // "User: Ann"
```

### str.ROOT([nobase])

Type: `method`

Antepone `DEF.root` o `DEF.baseurl` a un URL relativo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `nobase` | `Boolean` | no |  | Usa `true` per ignorare `DEF.baseurl`. |

Returns: `String` L'URL finale.

Viene usato `DEF.root` quando è impostato, altrimenti `DEF.baseurl`. Entrambi possono essere una stringa o una funzione che riceve l'URL e restituisce quello nuovo. Un prefisso stringa non viene aggiunto a un URL assoluto. Le barre ripetute nel risultato vengono ridotte a una sola. Vedi [DEF](../def/).

Example: Aggiungi un prefisso a un URL
```js
DEF.root = '/app';
'/users/'.ROOT(); // "/app/users/"
'https://www.totaljs.com/'.ROOT(); // "https://www.totaljs.com/"
DEF.root = '';

DEF.baseurl = '/base';
'/users/'.ROOT(); // "/base/users/"
'/users/'.ROOT(true); // "/users/"
DEF.baseurl = '';
```

### str.SCOPE(element)

Type: `method`

Sostituisce `?` in un path con il path dello scope di un elemento.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `Element, jQuery, Component, Plugin or Scope` | yes |  | L'oggetto che fornisce lo scope. |

Returns: `String` Il path finale.

Un path senza `?` viene restituito così com'è. Vedi [Scope](../../guides/scopes/).

Example: Risolvi un path con scope
```html
<ui-plugin path="orders"><div id="field"></div></ui-plugin>

<script>
PLUGIN('orders', function(exports) {});

setTimeout(function() {
	var path = '?.name'.SCOPE($('#field'));
	console.log(path);
}, 500);
</script>
```

### str.slug([max])

Type: `method`

Converte il testo in un identificatore minuscolo adatto agli URL.

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

Returns: `String` Lo slug.

I diacritici vengono convertiti con [toASCII()](#toascii). Spazi e punteggiatura diventano un singolo `-` e i caratteri senza una forma ASCII vengono rimossi.

Example: Crea uno slug
```js
'Hello World!'.slug(); // "hello-world"
'  Žluťoučký kůň  '.slug(); // "zlutoucky-kun"
'one two three'.slug(7); // "one-two"
```

### str.toASCII()

Type: `method`

Sostituisce i caratteri con diacritici con le rispettive lettere ASCII.

Returns: `String` Il testo convertito.

La conversione riguarda i caratteri `á ä č ď é ě í ï ĺ ľ ň ó ô ö ő ŕ ř š ť ú ů ü ű ý ÿ ž ć`, sia maiuscoli sia minuscoli. Gli altri caratteri restano invariati.

Example: Rimuovi i diacritici
```js
'Žluťoučký kůň'.toASCII(); // "Zlutoucky kun"
'Señor'.toASCII(); // "Señor"
```

### str.toSearch()

Type: `method`

Normalizza il testo per la ricerca approssimata.

Returns: `String` Il testo normalizzato.

Il metodo rimuove la punteggiatura tranne i due punti, converte il testo in ASCII minuscolo, sostituisce `y` con `i` e comprime i caratteri ripetuti.

Example: Normalizza un termine di ricerca
```js
'Žluťoučký Kůň!'.toSearch(); // "zlutoucki kun"
'Yellow Sunny'.toSearch(); // "ielow suni"
```

### str.VARIABLES([args])

Type: `method`

Legge le definizioni `--name=value--` dal testo e sostituisce i segnaposto `--name--`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `args` | `Object` | no |  | Valori predefiniti. Le definizioni trovate nel testo vengono aggiunte a questo oggetto. |

Returns: `String` Il testo elaborato.

Le definizioni vengono rimosse dal testo e memorizzate in `args`. Un segnaposto senza valore resta nel testo.

Example: Variabili in un testo
```js
'--color=red--Color: --color--'.VARIABLES(); // "Color: red"
'Size: --size--'.VARIABLES({ size: '10px' }); // "Size: 10px"
'Size: --size--'.VARIABLES(); // "Size: --size--"
```
