0

Here is my code and the problem is whether you search for "remember" or "member" it returns the result.As 'remember' has 'member' and I just want to search for exact matches. I should not return anything when I search for 'member'.

txt= `38
00:04:17.795 --> 00:04:23.551
Two previous cases
were open and shut.

39
00:04:23.601 --> 00:04:29.140
It was January 3, 1995,
my daughter's birthday.

40
00:04:29.140 --> 00:04:30.441
I remember.`

const searchedWord = 'member';
var res = txt
  .toLowerCase()
  .split('\n\n')
  .filter((x) => {
    return x.includes(searchedWord.toLowerCase());
  });

console.log(res);
mxd
  • 103
  • 8
  • That's what String.includes does--maybe it isn't the best way to search a string for a boundary-based complete word? (That's a hint.) – Dave Newton Dec 19 '21 at 15:45

1 Answers1

0

It sounds like you want to require word breaks on either side of the word you're searching for. You can do that with a regular expression:

const searchRegex = /\bmember\b/i; // ***
var res = txt
  .toLowerCase()
  .split('\n\n')
  .filter((x) => {
    return searchRegex.test(x);    // ***
  });

Live Example:

const txt = `38
00:04:17.795 --> 00:04:23.551
Two previous cases
were open and shut.

39
00:04:23.601 --> 00:04:29.140
It was January 3, 1995,
my daughter's birthday.

40
00:04:29.140 --> 00:04:30.441
I remember.

41
He was a member of the club

42
Something else`;

const searchRegex = /\bmember\b/i;
var res = txt
  .toLowerCase()
  .split('\n\n')
  .filter((x) => {
    return searchRegex.test(x);
  });

console.log(res);

If you need to create the regular expression dynamically (that is, starting with a string variable or similar containing "member"), see this question's answers and, if relevant, this one's.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875