How to extract space-separated words via Javascript

Asked

Viewed 408 times

3

Continuing the marathon of articles regarding the 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 remove my doubt and certainly that of other users, today’s problem is this:

Imagine that a var of the value string type has been declared:

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

In a situation, for example, where one should seek items filtering by name on a given list with name items X, instead of returning a value Undefined when the text typed in the field is not compatible with the name of any item in the list due to the search being exact, there is how to create a loop (for for example) where it will pick up word for word (separated by the space in the string) pada can thus do a more dynamic search within that list?

  • I put in methods to "break the sentence into pieces". Where are you going to use this? is in a search function like google you want to use every word to make a match?

  • Only I want one more condition in the match. The length of the words has to be greater than 1

  • How do I do that?

  • If the part you were missing was only what I answered you can mark the answer as accepted if you like. If you don’t show more code I can help you complete.

  • It’s this condition that I want now. I don’t want it to extract words like sizes smaller than 2

  • Then you can filter the results like palavras = palavras.filter(str => str.length > 2);

  • Answering your question: Yes! I want to use every word to make a match and return a specific value.

  • Make a jsFiddle with what you have that is easy to fix.

Show 3 more comments

1 answer

4


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);

  • 1

    Thanks! I’m glad for the attention to the problem. I imagine this will help me and many other users!

  • 1

    Now I can use for a word-by-word search! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.