Home > Software engineering >  JavaScript search using includes method in js with exact match
JavaScript search using includes method in js with exact match

Time:12-20

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

CodePudding user response:

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.

  • Related