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 );
}
This would create the following array:
var wordArray = ['never','forget','to','empty','your','vacuum','bags'];
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.
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.
push() The push() method adds one or more elements to the end of an array and returns the new length of the 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.
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);
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:
String.prototype.split()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With