0

I have to chech if some parts of a string are included into a bigger string, that is for a text search, like:

let search = "Joe is a good boy"
let text = "One of the better boys is Joe"

How can i do see if the whole string or a part of it is included into text? I tried to search.split() looking for every splitted string, but it's not good: i would like to search at least if there are partial matches on strings like "Joe", "Joe is", "Joee is a" ... etc.

Could you suggest me any function to do it?

  • What you mean by "part of the string" ? A word? A letter? Some substring longer than...? – georg Apr 28 '21 at 09:29
  • a word, or a substring... i guess – Massimo Ivaldi Apr 28 '21 at 09:31
  • https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript – mplungjan Apr 28 '21 at 09:31
  • You need to create an array like `["Joe is a good boy", "Joe is a good", "is a good boy", "Joe is a", "is a good", ...]` etc. (all parts, sorted by length). Then use `String.prototype.includes` to find the first match. If you question is how to get these parts in the first place: what have you tried so far? –  Apr 28 '21 at 09:33

1 Answers1

2

To check for common words, you can convert both strings into Sets of words and compute an intersection of these sets.

let search = "Joe is a good boy"
let text = "One of the better boys is Joe"


let words = str => new Set(str.split(/\s+/g))

let intersection = (a, b) => [...a].filter(x => b.has(x))

console.log(intersection(words(text), words(search)))

If you're looking for a LCS, see the duplicate thread.

georg
  • 211,518
  • 52
  • 313
  • 390
  • I don't think OP is looking for any words that match; it sounds like they're looking for the longest substring of the search string. –  Apr 28 '21 at 09:49