pushing each word to an array

2020-06-03 04:49发布

问题:

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 );
}
  1. go through every word in the string named words
  2. push that word to the array

This would create the following array:

var wordArray = ['never','forget','to','empty','your','vacuum','bags'];

回答1:

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