16

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
  • 15,447
  • 5
  • 79
  • 98
Hello World
  • 1,102
  • 2
  • 15
  • 33

5 Answers5

36

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
  • 249,100
  • 51
  • 377
  • 410
  • 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
5

Here's a possible rephrased version (non-regex):

An alternative solution that doesn't involve regular expressions could be considered.

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
  • 15,447
  • 5
  • 79
  • 98
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
  • 12,741
  • 2
  • 10
  • 29
0

Try below, it will help.

var wordArray = [];
var words = 'never forget to empty your vacuum bags';
wordArray = words.match(/\b[-?(\w+)?]+\b/gi);
console.log(wordArray)
0

I've tested out many methods from StackOverflow and other websites. The method that works for the majority of cases is the following:

function stringToArrayOfWords(str) {
    return str.split(' ').filter(w => w !== '')
}
McGrew
  • 812
  • 1
  • 9
  • 16