Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing each word to an array

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'];
like image 877
Hello World Avatar asked Nov 24 '13 00:11

Hello World


People also ask

Can you push multiple items into an array?

Use the Array. push() method to push multiple values to an array, e.g. arr. push('b', 'c', 'd'); . The push() method adds one or more values to the end of an array.

How do you split a string into an array of words?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

What does push do to an array?

push() The push() method adds one or more elements to the end of an array and returns the new length of the array.

How do you add items to each element in an array?

If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array. If you are using NumPy arrays, use the append() and insert() function.


2 Answers

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);
like image 195
Penny Liu Avatar answered Sep 25 '22 03:09

Penny Liu


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().
like image 29
David Thomas Avatar answered Sep 22 '22 03:09

David Thomas