If I had a string of text, how would I convert that string into an array of each of the individual words in the string?
Something like:
var wordArray = [];
var words = 'never forget to empty your vacuum bags';
for ( //1 ) {
wordArray.push( //2 );
}
- go through every word in the string named words
- push that word to the array
This would create the following array:
var wordArray = ['never','forget','to','empty','your','vacuum','bags'];
Don't iterate, just use split()
which returns an array:
let words = 'never forget to empty your vacuum bags',
wordArray = words.split(' ');
console.log(wordArray);
JS Fiddle demo.
And, using String.prototype.split()
with the regular expression suggested by @jfriend00 (in comments, below):
let words = 'never forget to empty your vacuum bags',
wordArray = words.split(/\s+/);
console.log(wordArray);
References:
- Regular Expressions.
String.prototype.split()
.