Convert string to array in JavaScript

In this tutorial, we will learn how to convert string to array in JavaScript.

Converting String to a character array in JavaScript

Variables used in code

  • str – string
const str = "This is a Tutorial in CodeSpeedy"

Method 1

We are going to use the split() method by passing the spiltBy string as “”.

let arr = str.split("")
console.log(arr)

Method 2

We are going to use Array.from() method and pass string str as an argument to it.

let arr = Array.from(str)
console.log(arr)

Method 3

Instead of using the built-in functions, I wrote a custom function. Basically, we pushed every character to the array.

let arr = []
for(let s in str){
    arr.push(str[s])
}
console.log(arr)

Using For In to a string loop to the index of the characters in a string.

Output

["T", "h", "i", "s", " ", "i", "s", " ", "a", " ", "T", "u", "t", "o", "r", "i", "a", "l", " ", "i", "n", " ", "C", "o", "d", "e", "S", "p", "e", "e", "d", "y"]

Converting String to an array of words in JavaScript

Variables used in code

  • str – string
const str = "This is a Tutorial in CodeSpeedy"

Method 1

We are going to use the split() method by passing the spiltBy string as ” “.

let arr = str.split(" ")
console.log(arr)

Method 3 

Instead of using the built-in functions, I wrote a custom function.

let arr = []
let i = 0
while(i!=-1 & i<=str.length){
    let index = str.indexOf(" ",i)
    if (index!=-1){
        arr.push(str.slice(i,index))
        i = index+1
    }
    else{
  	arr.push(str.slice(i))
        i = -1
    }
}
console.log(arr)

Output

["This", "is", "a", "Tutorial", "in", "CodeSpeedy"]

Also read: how to split a string in javascript with built-in and custom function

Leave a Reply

Your email address will not be published.