Home  >  Article  >  Web Front-end  >  js front-end fuzzy query implementation code

js front-end fuzzy query implementation code

小云云
小云云Original
2018-02-24 14:21:281754browse

First of all, you must understand what a fuzzy query is (nonsense 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 no match is found, it returns empty. Of course, there are several other methods that can be implemented, which will not be listed here.

//字符串方法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;
//正则表达式
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;

Related recommendations:
AngularJS fuzzy query function implementation code

php Fuzzy query implementation method

What is fuzzy query in php

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

Statement:
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