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.
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(); });
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.