Home > Web Front-end > JS Tutorial > Detailed explanation of js implementation of front-end fuzzy query

Detailed explanation of js implementation of front-end fuzzy query

小云云
Release: 2018-03-15 15:43:17
Original
2194 people have browsed it

For fuzzy queries, keywords are generally passed to the backend, and the backend does it. But sometimes some lightweight list front-ends can reduce ajax requests and improve user experience to a certain extent. Without further ado, let’s get straight to the code.

//字符串方法indexOf
var len = list.length;
var arr = [];
for(var i=0;i<len;i++){
    //如果字符串中不包含目标字符会返回-1
    if(list[i].indexOf(keyWord)>=0){
        arr.push(list[i]);
    }
}
return arr;
Copy after login
//正则表达式
var len = list.length;
var arr = [];
var reg = new RegExp(keyWord);
for(var i=0;i<len;i++){
    //如果字符串中不包含目标字符会返回-1
    if(list[i].match(reg)){
        arr.push(list[i]);
    }
}
return arr;
Copy after login

First of all, you must understand what a fuzzy query is (the nonsense comes again), which is to list the keywords in the list based on the keywords (of course, only the simplest ones are done here) , that is, to check whether each item in the list contains a keyword, so abstractly it means whether a string contains a certain character or string.

With the idea, the next step is to implement it. What method should be used? When learning the basic data types of js, we will find that String has many methods, among which there is the method string.indexOf(''); this The method is to find the position of a certain character in the string, and -1 will be returned if there is no target character. So we can use this method to check whether each item in the list contains a keyword. Next is the very powerful RegExp, a regular expression to match the target character of a string. The match method is used here. If it cannot match, it returns empty. Of course, there are several other methods that can be implemented, which will not be listed here.

Related recommendations:

Input-based dynamic fuzzy query

js front-end fuzzy query implementation code

php Fuzzy query implementation method

The above is the detailed content of Detailed explanation of js implementation of front-end fuzzy query. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template