How can I put each word of a string into an array in Javascript?

I have an string like so

var user = "henry, bob , jack";

How can I make that into an array so I could call

user[0]

and so on.

Upvotes: 1

Views: 1490

Answers (3)

iaretiga
iaretiga

Reputation: 5205

The String.prototype.split method splits a string into an array of strings, using a delimiter character. You can split by comma, but then you might have some whitespace around your entries.

You can use the String.prototype.trim method to remove that whitespace. You can use Array.prototype.map to quickly trim every item in your array.

ES2015:

const users = user.split(',').map(u => u.trim());

ES5:

var users = user.split(',').map(function(u) { return u.trim(); });

Upvotes: 1

isvforall
isvforall

Reputation: 8926

You can use String.prototype.split() and Array.prototype.map() functions for getting an array. And String.prototype.trim() for removing unnecessary spaces.

var user = "henry, bob , jack";

user = user.split(',').map(e => e.trim());

document.write(user[0]);

Upvotes: 0

Alex Shesterov
Alex Shesterov

Reputation: 27525

Use the string's split method which splits the string by regular expression:

var user = "henry, bob , jack";
var pieces = user.split(/\s*,\s*/);
// pieces[0] will be 'henry', pieces[1] will be 'bob', and so on. 

The regular expression \s*,\s* defines the separator, which consists of optional space before the comma (\s*), the comma and optional space after the comma.

Upvotes: 0

Related Questions