14

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'];
Penny Liu
  • 11,885
  • 5
  • 66
  • 81
Hello World
  • 962
  • 2
  • 15
  • 31

3 Answers3

31

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:

David Thomas
  • 240,457
  • 50
  • 366
  • 401
  • 4
    Might want to handle multiple spaces with `.split(/\s+/)`. – jfriend00 Nov 24 '13 at 01:32
  • 1
    @Wendy: everything in JavaScript is an Object, including Arrays. If you try running `console.log( wordArray instanceof Array )` that *should* result in `true`, unless that's what you already tried? But since `String.prototype.split()` always returns an Array (so far as I'm aware, from reading the docs a few times), I'm fairly confident it's an Array that's returned. – David Thomas Jan 28 '17 at 23:40
2

Another solution for non-regex option.

let words = '     practice   makes   perfect  ',
  wordArray = words.split(' ').filter(w => w !== '');

console.log(wordArray);

or just use String.prototype.match()

let words = '     practice   makes   perfect  ',
  wordArray = words.match(/\S+/g);

console.log(wordArray);
Penny Liu
  • 11,885
  • 5
  • 66
  • 81
1

If you wanted to iterate through the array use:

let wordArray = [];
let words = 'never forget to empty your vacuum bags';

let wordsSplit = words.split(" ");
for(let i=0;i<wordsSplit.length;i++) {
    wordArray.push(wordsSplit[i])
}

But it would make more sense to not iterate and just use:

let words = 'never forget to empty your vacuum bags';
let arrOfWords = words.split(" ")
lpizzinidev
  • 5,706
  • 1
  • 6
  • 19