[javascript] Split string into array

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

The answer is


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


ES6 :

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to split

Parameter "stratify" from method "train_test_split" (scikit Learn) Pandas split DataFrame by column value How to split large text file in windows? Attribute Error: 'list' object has no attribute 'split' Split function in oracle to comma separated values with automatic sequence How would I get everything before a : in a string Python Split String by delimiter position using oracle SQL JavaScript split String with white space Split a String into an array in Swift? Split pandas dataframe in two if it has more than 10 rows