Dividi stringa in array in JavaScript

Harshit Jindal 12 ottobre 2023
  1. Usa il metodo split() per dividere una stringa in un array in JavaScript
  2. Usa il metodo from() per dividere una stringa in un array in JavaScript
  3. Usa l’operatore spread ES6 per dividere una stringa in un array
Dividi stringa in array in JavaScript

Questo tutorial insegna come dividere una stringa in un array in JavaScript.

Usa il metodo split() per dividere una stringa in un array in JavaScript

Il metodo split() prende come input una stringa e restituisce un array di sottostringhe che sono formate in base a un delimitatore. Questa condizione di suddivisione viene fornita come primo argomento della funzione. Se non diamo argomenti, otteniamo un array contenente una copia della stringa. Se forniamo un delimitatore, la funzione divide la stringa in un array di sottostringhe separate da quel carattere. Quindi, se vogliamo ottenere ogni carattere come elemento dell’array, dobbiamo fornire "" come argomento.

var arr = 'delftstack'.split('');
console.log(arr);

Produzione:

["d", "e", "l", "f", "t", "s", "t", "a", "c", "k"]

Usa il metodo from() per dividere una stringa in un array in JavaScript

Il metodo from() prende come input un array e restituisce un altro array. Se forniamo una stringa come input, crea un array con ogni carattere della stringa come elemento dell’array. Prende come argomenti i seguenti parametri:

  1. object: è l’oggetto di input che deve essere convertito in un array.
  2. mapFunction: è un argomento opzionale che specifica la funzione map da chiamare sugli elementi dell’array.
  3. thisValue: Si usa per rappresentare il valore this dell’oggetto nella mapFunction.
console.log(Array.from('delftstack'));

Usa l’operatore spread ES6 per dividere una stringa in un array

L’operatore spread decomprime gli oggetti iterabili. Itera su qualsiasi oggetto iterabile e lo espande sul posto. Quando l’operatore spread viene utilizzato su una stringa, otteniamo un array di sottostringhe in cui ogni sottostringa è un singolo carattere della stringa.

const str = 'delftstack';
const arr = [...str];
console.log(arr);

I browser come Internet Explorer non supportano questo operatore.

Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn

Articolo correlato - JavaScript Array

Articolo correlato - JavaScript String