簡體   English   中英

過濾匹配字符序列的 JavaScript 字符串數組

[英]Filter a JavaScript array of strings matching a sequence of characters

如何有效地過濾與字符序列匹配的字符串數組,以便字符可以在字符串中的任何位置但按使用順序匹配?

這是一個在編輯器和 IDE 中常見的功能,可以快速過濾文件名。

在附加的圖像鏈接中查看正在運行的過濾器的插圖。

過濾器在行動中的插圖

這不是沒有外部庫JavaScript 自動完成的副本,因為這里的要求之一是用戶輸入“Caz”與“滄州”匹配,這在這個問題的答案中有所解釋,而不是在其他問題的答案中。

我認為這應該非常接近。 答案嘗試構建一個正則表達式,使其按照字符在搜索詞中出現的順序進行匹配。

 const values = ['Brussels', 'Cairo', 'Casablanca', 'Cangzhou', 'Caracas', 'Los Angeles', 'Osaka']; const match = (s) => { const p = Array.from(s).reduce((a, v, i) => `${a}[^${s.substr(i)}]*?${v}`, ''); const re = RegExp(p); return values.filter(v => v.match(re)); }; console.log(match('Ca')); // Cairo, Casablanca, Cangzhou, Caracas console.log(match('Caz')); // Cangzhou console.log(match('as')); // Casablanca, Caracas console.log(match('aa')); // Casablanca, Caracas, Osaka

這實際上比看起來更簡單。 此外,當前接受的解決方案實際上並不一致。

您只需要構造一個正則表達式,它在搜索字符串的每個字符之間接受 0 個或多個字符。

const values = ['Belgium', 'Brest', 'Britian']
const query = 'Be'

// /.*b.*e.*/
const re = RegExp(`.*${query.toLowerCase().split('').join('.*')}.*`)

// [ 'Belgium', 'Brest' ]
const matches = values.filter(v => v.toLowerCase().match(re))

這是一個例子。

為了減少意外錯誤,您應該將輸入值限制為您希望輸入的值。

 var all = ['test','string','array','example']; function getMatch(arr, str){ var reg = new RegExp(str.split('').join('.*'), 'i'); return arr.filter(function(item) { if (item.match(reg)) { return item; } }); } function search(value){ document.getElementById("result").innerHTML = getMatch(all, value); }
 <input type="text" onkeyup="search(this.value)"> <br /> <span id="result"></span>

這個簡單的例子使用了正則表達式和Array.prototype.filter()

 var strings = ["Cairo", "Casablanca", "Cangzhou", "Carcas"]; // Your array of things to filter function disp(matches) { // Displays the filtered results on the page var results = document.getElementById("suggestions"); results.innerHTML = matches.join("<br>"); } function regExpTest(inputString, regex) { // Checks to see if what the user typed matches any items in gucciArray return regex.test(inputString); } function typeKey(event) { // This function is supposed to be called whenever the user types a letter in the text box var textTyped = event.target.value; // What the user typed in the text box; var filter = new RegExp(textTyped.split('').join('.*'), 'i'); // Matches anything with the characters that the user typed, in order, with any characters inbetween them // Filter the array // Returns a new array containing the items from the old array that pass the RegExp test var filteredArray = strings.filter(s => regExpTest(s, filter)); // Display the filtered results on the page disp(filteredArray); } disp(strings);
 <html> <head> </head> <body> Type here: <input type="text" onkeyup="typeKey(event);"> <br> List of matches: <div id="suggestions"></div> </body> </html>

disp是可選的。 它僅用於交互式代碼片段。 如果您想獲取稍后使用的值,請將typeKey的最后一行替換為return newArray;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM