In addition to the indexOf and includes methods, let’s take a look at the match method

1. In the past, the original indexOf method was used to deal with the simple fuzzy search function, and ES6 came out with the includes method. In fact, the effect is the same, but the includes method returns a boolean value, if letter case retrieval is involved , Then there is a problem, such as

// indexOf()
let str = 'AbcdEFG';
str.indexOf('bc');//1
str.indexOf('bcD');//-1 
// includes()
str.includes('bc');//true
str.includes('bcD');//false

From the above output results, I can draw a conclusion. I think there should be someone who will specially convert the letters entered by the user through the toLowerCase() and toUpperCase() methods and then search for judgment. At least I came here as a novice. of.

2. Let's take a look at the match method below

match(searchvalue||regexp) This method has only one parameter, either the retrieved string or the RegExp object. If you only pass in a string to retrieve, the effect is the same as the above two methods, so we need Use RegExp object to retrieve

//还是继续使用上面的str变量,这次我们在RegExp对象加上 /i 忽略大小写功能

// 正常检索
str.match(new RegExp('Abc', 'i'));//["Abc", index: 0, input: "AbcdEFG", groups: undefined]
// 忽略大小写检索
str.match(new RegExp('ABC', 'i'));//["Abc", index: 0, input: "AbcdEFG", groups: undefined]
// 无法正常检索
str.match(new RegExp('ABCABC', 'i'));//null

With the results retrieved by the above match method, we can judge whether the retrieval is successful by the length of the array or whether it is an array. You can see the demo below


const arr = [{
    
    name:'测试_test'},{
    
    name:'后_端sTE'},{
    
    name:'前端Stb'},{
    
    name:'运维pp_k'},{
    
    name:'_安卓AteSTdn'},{
    
    name:'苹果Apple'}]
let value = 'Te';
let res = arr.filter(item => {
    
    
    let len = item.name.match(new RegExp(value,'i'));
    return len&&len.length&&item;
})
console.log(res);//[{name: "测试_test"},{name: "后_端sTE"},{name: "_安卓AteSTdn"}]

Guess you like

Origin blog.csdn.net/hzw29106/article/details/109363595