Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript function to search like in vscode files

I'm trying to understand how to make a dropdown search function in javscript that works like file-search CTRL+P in vscode. The search query to be automatically including wildcards.
For example i type inds and vscode finds index.js file. How to make something similar in javscript using indexOf for example?

Thank you

like image 793
Kiril Lukiyan Avatar asked Jul 16 '26 19:07

Kiril Lukiyan


2 Answers

What you are looking for is called fuzzy finders. You can find a lot of packages out there just by googling it.

Fuzzy searching allows for flexibly matching a string with partial input, useful for filtering data very quickly based on lightweight user input.

E.g:

  • Fuse.js
  • Fuzzysearch
  • etc
like image 79
Eugene Obrezkov Avatar answered Jul 19 '26 09:07

Eugene Obrezkov


Here's a quick hack to imitate VSC fuzzy finder (symbol search, file search, etc.):

function fuzzyFindInArray(words, searchTerm = "") {
  if (!searchTerm) {
    return words;
  }
  const regex = new RegExp(`${searchTerm.split("").join("+?.*")}`, "i");
  return words.filter((word) => regex.test(word));
}

const words = ["hello", "yellow", "lower"];

console.log("eo", fuzzyFindInArray(words, "eo"));
console.log("lo", fuzzyFindInArray(words, "lo"));
console.log("ho", fuzzyFindInArray(words, "ho"));
console.log("y", fuzzyFindInArray(words, "y"));
console.log("low", fuzzyFindInArray(words, "low"));
console.log("e", fuzzyFindInArray(words, "e"));

I have not benchmarked performance on the following function, since I am using it with small-ish arrays (hundreds of items). Also, results are not sorted, and would need something like RegExp groups to highlight matched letters (regex approach).

like image 32
RobertoNovelo Avatar answered Jul 19 '26 07:07

RobertoNovelo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!