欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

除了indexOf和includes方法,不妨来了解一下match方法

程序员文章站 2022-11-05 08:28:37
1.以前做项目都是用原生的indexOf方法去处理简单模糊检索功能,后面ES6出来用includes方法,其实效果都是一样的,只是includes方法返回的是布尔值,如果涉及到字母大小写检索的话,那就有问题了,比如// indexOf()let str = 'AbcdEFG';str.indexOf('bc');//1str.indexOf('bcD');//-1 // includes()str.includes('bc');//truestr.includes('bcD');//fal....

1.以前做项目都是用原生的indexOf方法去处理简单模糊检索功能,后面ES6出来用includes方法,其实效果都是一样的,只是includes方法返回的是布尔值,如果涉及到字母大小写检索的话,那就有问题了,比如

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

通过以上输出结果可以得出结论,我觉得应该会有人在工作上会特地去将用户输入的字母通过toLowerCase() 和toUpperCase()方法转换然后再去检索判断吧,最起码新手时我是这样过来的。

2.下面我们来看下match方法吧

match(searchvalue||regexp) 这方法参数只有一个,要么是检索的字符串,要么是RegExp对象,如果只是传 入字符串去检索的话,那作用跟上面两个方法效果是一样的,所以我们需要用RegExp对象去检索

//还是继续使用上面的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

通过以上match方法检索出来的结果我们可以通过数组的长度或者判断是否是数组来判断是否有检索成功,可以看下面demo


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"}]

本文地址:https://blog.csdn.net/hzw29106/article/details/109363595

相关标签: 前端那些事