Convert string to array JavaScript Code Example

Last Updated On Wednesday 13th Apr 2022

String to Array

	String -> "Today was a very cold day"
Array -> ["Today","was","a","very","cold","day"]
	String -> "Wonderful"
Array -> [
  'W', 'o', 'n',
  'd', 'e', 'r',
  'f', 'u', 'l'

Example 1: Split Method

What is the Split method?

  • The JavaScript split method splits a string into an array of substrings.
  • So, this is a string split into an array of substrings from string to Array.
  • The split method takes two arguments.
  • They’re both optional.
  • They are separator and limit.
  • It’s upto You where and how to split.
	let arr = 'This is going to be Fun';
let res = arr.split(' ')

The Above code Produce the below output.

	// [ 'This', 'is', 'going', 'to', 'be', 'Fun' ]

Example 2 : Array.from

What is the Array.from() ?

  • Array.from method makes Array-like Objects (such as the NodeList) and other iterable Objects (such as an Object or String) to Array.
  • The Array.from() method also lets you optionally pass in a modifier function you can use to transform the items in the Array.
	let arr = 'HappyDay';
let res = Array.from(arr);

The Above code Produce the below output

	// [
//  'H', 'a', 'p',
//  'p', 'y', 'D',
//  'a', 'y'
// ]

With Modifier

  • Let’s we want every letter to be in uppercase.
	let arr = 'HappyDay';

let res = Array.from(arr, a => a.toUpperCase());
	// [
//  'H', 'A', 'P',
//  'P', 'Y', 'D',
//  'A', 'Y'
// ]
  • The Array.from() method works in all modern browsers.

Example 3: For of Loop JavaScript

What is for of Loop?

  • The for of loop assigns each element, in turn, a loop variable.
  • We loop through each character and push that each into a new empty Array
	let arr = 'Awesome';

let res = [];

for (const each of arr) {

The Above code Produce the below output.

	// [
//  'A', 'w', 'e',
//  's', 'o', 'm',
//  'e'
// ]
  • The each variable is scoped to the curly-braced code block.
  • Define your loop variables as const to prevent accidental modification of array elements.