정태현
정태현

Reputation: 29

Find word in sentence in javascript?

I have set lists

example:

const answerList = [{index: 2, answer: nice}, {index: 5, answer: sunday} ...] 

like that

and I have a sentence

example:

"hi i'm theo nice to meet you. how are you"

so I want to check if there is a correct answer in the sentence and if find it, return answerList set

example:

return value is [{index: 2, answer: nice}]

Because there is the word "nice" in the sentence.

Can someone tell me a good way?

Upvotes: 0

Views: 263

Answers (1)

Mamun
Mamun

Reputation: 68943

You can try using Array.prototype.filter() and String.prototype.includes():

const answerList = [{index: 2, answer: 'nice'}, {index: 5, answer: 'sunday'}];
const sentence = "hi i'm theo nice to meet you. how are you";
var res = answerList.filter(a => sentence.includes(a.answer));
console.log(res);

Upvotes: 2

Related Questions