How can I split a JavaScript string by white space or comma?
String.split()
can also accept a regular expression:
input.split(/[ ,]+/);
This particular regex splits on a sequence of one or more commas or spaces, so that e.g. multiple consecutive spaces or a comma+space sequence do not produce empty elements in the results.
The suggestion to use .split(/[ ,]+/)
is good, but with natural sentences sooner or later you'll end up getting empty elements in the array. e.g. ['foo', '', 'bar']
.
Which is fine if that's okay for your use case. But if you want to get rid of the empty elements you can do:
var str = 'whatever your text is...';
str.split(/[ ,]+/).filter(Boolean);
you can use regex in order to catch any length of white space, and this would be like:
var text = "hoi how are you";
var arr = text.split(/\s+/);
console.log(arr) // will result : ["hoi", "how", "are", "you"]
console.log(arr[2]) // will result : "are"