JavaScript 中的模糊搜尋演算法
我們需要編寫一個 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
廣告