简体   繁体   English

过滤匹配字符序列的 JavaScript 字符串数组

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

How can I efficiently filter an array of strings matching a sequence of characters, such that characters may be matched anywhere in the string but in the order they are used?如何有效地过滤与字符序列匹配的字符串数组,以便字符可以在字符串中的任何位置但按使用顺序匹配?

It's a feature commonly seen in editors and IDEs to quickly filter filenames.这是一个在编辑器和 IDE 中常见的功能,可以快速过滤文件名。

See an illustration of the filter in action in the attached image link.在附加的图像链接中查看正在运行的过滤器的插图。

过滤器在行动中的插图

This is not a duplicate of JavaScript autocomplete without external library , because one of the requirements here is for user input "Caz" to match "Cangzhou" which is explained in the answer to this question, but not in the answers to other questions.这不是没有外部库JavaScript 自动完成的副本,因为这里的要求之一是用户输入“Caz”与“沧州”匹配,这在这个问题的答案中有所解释,而不是在其他问题的答案中。

I think this should be pretty close.我认为这应该非常接近。 The answer tries to build a regular expression to make it so that characters are matched in the order they appear in the search term.答案尝试构建一个正则表达式,使其按照字符在搜索词中出现的顺序进行匹配。

 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

This is actually simpler than it looks.这实际上比看起来更简单。 Also, the currently accepted solution does not actually work consistently.此外,当前接受的解决方案实际上并不一致。

You simply need to construct a regex that accepts 0 or more characters between each character of the search string.您只需要构造一个正则表达式,它在搜索字符串的每个字符之间接受 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))

Here is an example for that.这是一个例子。

To reduce error unexpected, you should limit the input value to what you want they key in.为了减少意外错误,您应该将输入值限制为您希望输入的值。

 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>

This simple example uses a Regular Expression and Array.prototype.filter()这个简单的例子使用了正则表达式和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 is optional. disp是可选的。 It's just for the interactive code snippet.它仅用于交互式代码片段。 If you want to get the values to use later, replace the last line in typeKey with return newArray;如果您想获取稍后使用的值,请将typeKey的最后一行替换为return newArray;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM