How to extract space-separated words via Javascript

3

Continuing the marathon of articles regarding extraction of texts, I noticed that this type of question is very difficult to find next to a clear and direct answer.

In order to take away my doubt and certainly the one of other users, today's problem is this:

Imagine that a var of a value string type was declared:

var texto = "Eu quero tirar minhas duvidas sobre Javascript"

In a situation, for example, where you should look for items by filtering by name in a particular list with X items instead of returning a value undefined when the text entered in the field does not match the name of any item in the list because the search is exact , there is a loop for < in> for example) where it will get word by word (separated by space in the string) so you can do a more dynamic search within that list?

    
asked by anonymous 14.05.2017 / 14:25

1 answer

3

Using RegExp:

var texto = "Eu quero tirar minhas duvidas sobre Javascript";
var palavras = texto.match(/[^\s]+/g);
console.log(palavras);

Using .split() :

var texto = "Eu quero tirar minhas duvidas sobre Javascript";
var palavras = texto.split(' ');
console.log(palavras);
    
14.05.2017 / 14:27