Convert string to array in javascript

Learn different approaches to convert string to array of characters in javascript. Everything will be written in ES6.

Using split()

split() method creates an array of substrings by breaking the string at a specific separator.

let str = 'learnersbucket';
let strArray = str.split('');
console.log(strArray);
// ["l", "e", "a", "r", "n", "e", "r", "s", "b", "u", "c", "k", "e", "t"]

The split(separator, limit) method takes two parameters.

  • separator: An idendifier at which the string will be split into substrings.
  • limit(optional): No of substrings to be returned.
let str = 'is javascript wierd language';
let strArray = str.split(' ', 2);
console.log(strArray);
//["is", "javascript"]

The above method splits the string at whitespace ' ' and returns array with two substrings.

This method does not mutates the original string.

let str = 'is,javascript,wierd,language';
let strArray = str.split(',');

console.log(strArray);
//["is", "javascript", "wierd", "language"]

console.log(str);
//"is,javascript,wierd,language"

Iterative approach

We can also iterate through each character of the string and then create an array of characters or substrings.

let str = 'learnersbucket';
let strArray = [];
for(let char of str){
  strArray.push(char);
}

console.log(strArray);
//["l", "e", "a", "r", "n", "e", "r", "s", "b", "u", "c", "k", "e", "t"]

Converting string into array of substrings

We can also use custom conditions to create substrings and then add it to the array.

let str = 'is,javascript,wierd,language';
let strArray = [];

//Temp string
let temp = '';

for(let char of str){
  
  //if current character is ,
  if(char === ','){
    //then push the substring
    strArray.push(temp);
    temp = '';
    continue;
  }
  
  //Create substring
  temp += char;
};

//Push the last substring
strArray.push(temp);

console.log(strArray);
//["is", "javascript", "wierd", "language"]

Leave a Reply

Your email address will not be published. Required fields are marked *