Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into array [duplicate]

In JS if you would like to split user entry into an array what is the best way of going about it?

For example:

entry = prompt("Enter your name")  for (i=0; i<entry.length; i++) { entryArray[i] = entry.charAt([i]); }  // entryArray=['j', 'e', 'a', 'n', 's', 'y'] after loop 

Perhaps I'm going about this the wrong way - would appreciate any help!

like image 882
methuselah Avatar asked Nov 02 '11 11:11

methuselah


2 Answers

Use the .split() method. When specifying an empty string as the separator, the split() method will return an array with one element per character.

entry = prompt("Enter your name") entryArray = entry.split(""); 
like image 192
James Hill Avatar answered Sep 18 '22 17:09

James Hill


ES6 :

const array = [...entry]; // entry="i am" => array=["i"," ","a","m"] 
like image 22
Abdennour TOUMI Avatar answered Sep 19 '22 17:09

Abdennour TOUMI