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!
This question is related to
javascript
arrays
string
split
Use split
method:
entry = prompt("Enter your name");
entryArray = entry.split("");
Refer String.prototype.split()
for more info.
var foo = 'somestring';
// bad example https://stackoverflow.com/questions/6484670/how-do-i-split-a-string-into-an-array-of-characters/38901550#38901550
var arr = foo.split('');
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]
// good example
var arr = Array.from(foo);
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]
// best
var arr = [...foo]
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]
...and also for those who like literature in CS.
array = Array.from(entry);
use var array = entry.split("");
You can try this:
var entryArray = Array.prototype.slice.call(entry)
You can try this way:
let entry = prompt("Enter your name")
let entryArray = entry.split('')
console.log(entryArray)
here is fiddle https://jsfiddle.net/swapanil/Lp1arvqc/17/
ES6 is quite powerful in iterating through objects (strings, Array, Map, Set). Let's use a Spread Operator to solve this.
entry = prompt("Enter your name");
var count = [...entry];
console.log(count);
Do you care for non-English names? If so, all of the presented solutions (.split(''), [...str], Array.from(str), etc.) may give bad results, depending on language:
"????? ???????".split("") // the current president of India, Pranab Mukherjee
// returns ["?", "?", "?", "?", "?", " ", "?", "?", "?", "?", "?", "?", "?"]
// but should return ["??", "?", "?", "?", " ", "??", "?", "??", "??"]
Consider using the grapheme-splitter library for a clean standards-based split: https://github.com/orling/grapheme-splitter
const array = [...entry]; // entry="i am" => array=["i"," ","a","m"]
Source: Stackoverflow.com