Split string into array

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 04:02:53

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("");

ES6 :

const array = [...entry]; // entry="i am" => array=["i"," ","a","m"]

use var array = entry.split("");

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

You can try this:

var entryArray = Array.prototype.slice.call(entry)

...and also for those who like literature in CS.

array = Array.from(entry);
Lukman

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"]

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!