Share with   

Convert string into comma separated array list in JavaScript

Here we are converting comma separated string into array list using JavaScript. So we can use this in every js framework like angular, react, vuejs etc.


Converting comma separated string into array list using JavaScript having 2 methods i.e.

1) Using split() method

2) Iterating with string and slicing string to comma and push to array.

 

Examples

Method 1 : Using split() method

Syntax for converting array

var temp_string = "One, Two, Three, Four, Five"
var temp_arr = new Array();
temp_arr = res.CustomerAssignGroupIds.split(", ");
console.log(temp_arr)

 

Check Sample HTML Demo

<!DOCTYPE html> 
<html> 
  <head> 
  	<title> 
  	   Convert comma separated string to array using JavaScript 
    </title> 
  </head> 
  <body> 
  	<h1 style="color: blue"> ProCodeProgramming </h1> 
  	<b>Convert comma separated string 
  	to array using JavaScript</b> 
  	<p>Original string is "One, Two, Three, Four, Five"</p> 
  	<p>Separated Array is: <span class="output"></span></p> 
  	<button onclick="separateString()"> 
  	      Remove Text 
    </button> 
  	<script type="text/javascript"> 
  		function separateString() { 
  			originalString = "One, Two, Three, Four, Five"; 
  			separatedArray = originalString.split(', '); 
  			console.log(separatedArray); 
  			document.querySelector('.output').textContent = 
  			separatedArray; 
  		} 
  	</script> 
  </body> 
</html> 

 

Output

 

Method 2 : Iterating with string and slicing string to comma and push to array.

Syntax for slicing string using for loop

originalString = "Bhushan, Amit, Maya, Pratik, Shanaya"; 
separatedArray = []; 
 
// index of end of the last string  
let previousIndex = 0; 
 
for(i = 0; i < originalString.length; i++) { 
 
    // check the character for a comma 
    if (originalString[i] == ', ') { 
 
        // split the string from the last index 
        // to the comma 
        separated = originalString.slice(previousIndex, i); 
        separatedArray.push(separated); 
 
        // update the index of the last string 
        previousIndex = i + 1; 
    } 
} 
 
// push the last string into the array 
separatedArray.push(originalString.slice(previousIndex, i));

 

Thank you for watching article. If you want learn more about java script please check our javascript tutorials.

Author Image
Guest User

0 Comments