skip to Main Content

How to search for all matches of words in the description field?
Now it works if you enter words completely, but by the condition the user can enter words not completely, but only part of them. For example (Exampl Sampl) then the expression does not work.

const search = 'Example1 Sample2'
var exp = new RegExp("(?=.*?(?:\s|^)" + search.replace(/ /g, "(?:\s|$))(?=.*?(?:\s|^)") + "(?:\s|$))", 'gi');
eventsFiltered = eventsFiltered.filter((e) => {
    return !!(exp.test(e.description));
});

2

Answers


  1. Try this

    const search = 'Example1 Sample2';
    const searchTerms = search.split(' ');
    
    const searchTermPatterns = searchTerms.map(term => {
      const escapedTerm = term.replace(/[-/\^$*+?.()|[]{}]/g, '\$&');
      return `(?=.*\b${escapedTerm})`;
    }).join('');
    
    const regexPattern = new RegExp(searchTermPatterns, 'gi');
    
    eventsFiltered = eventsFiltered.filter(e => regexPattern.test(e.description));
    
    1. The regular expression pattern you’ve constructed contains the
      entire search string without considering partial matches.
    2. The search.replace(/ /g, "(?:s|$)) part of the pattern is causing
      incorrect behavior for partial word matching.
    Login or Signup to reply.
  2. You could use a simpler approach and just use String::includes() and make sure every word in the search string is included in the description:

    const eventsFiltered  = [{description: 'Example1 Sample2 Проверка'}, {description: 'Example Проверка'}];
    const search = 'Exampl Sampl Провер';
    const result = eventsFiltered.filter(({description}) => search.match(/S+/g).every(word => description.includes(word)));
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search