JavaScript 中的模糊搜索算法

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/11 17:48:17

我们需要编写一个 JavaScript 字符串函数,该函数接收一个搜索字符串,并松散地检查它所使用的字符串中是否存在搜索字符串。

该函数应考虑以下标准: 它应循环遍历搜索查询字母并检查它们是否以相同的顺序出现在字符串中。

例如 −

('a haystack with a needle').fuzzySearch('hay sucks'); // false
('a haystack with a needle').fuzzySearch('sack hand'); // true

示例

const fuzzySearch = function (query) {
   const str = this.toLowerCase();
   let i = 0, n = -1, l;
   query = query.toLowerCase();
   for (; l = query[i++] ;){
      if (!~(n = str.indexOf(l, n + 1))){
         return false;
      };
   };
   return true;
};
String.prototype.fuzzySearch = fuzzySearch;
console.log(('a haystack with a needle').fuzzySearch('hay sucks'));
console.log(('a haystack with a needle').fuzzySearch('sack hand'));

输出

这将产生以下输出 −

false
true

相关文章


有用资源