pushing each word to an array

2020-06-03 04:26发布

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条回答
【Aperson】
2楼-- · 2020-06-03 05:13

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:

查看更多
登录 后发表回答