栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

ES6使用正则表达式过滤数组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ES6使用正则表达式过滤数组

首先,

new RegExp('/bcontactb', 'g');
它等于
//@contact@/g
哪里
@
是退格字符(ASCII
08)…显然不是您想要的

所以,你会做的

new RegExp('/\bcontact\b', 'g');
-这相当于
//bcontactb/g

但是,

\b
之后
/
是多余的

所以…到

//contactb/g

string.match
在这里使用
regex.test
被滥用。以下是说明

var sites = {     links: [        {href: 'https://www.example.com/v1/contact-us/ca'},        {href: 'https://www.example.com/v1/contact-us/au'},        {href: 'https://www.example.com/v1/contact-us/us'},        {href: 'https://www.example.com/v1/dontcontact-us/us'}    ]};const regex = new RegExp('/contact\b', 'g');const matchedSites = sites.links.filter(({href}) => href.match(regex));console.log(matchedSites);

下一个问题是在

regexp.test
with
g
标志中多次使用ONE正则表达式。每次调用,它将目光从未来
indexOf
先前FOUND子,并在同一类型的字符串的连续调用,它基本上会返回
true
false
true
false

如果要使用

regex.test
,则不要重复使用相同的正则表达式,除非您知道这样做的后果或不使用
g
标志(此处不需要)

var sites = {    links: [        {href: 'https://www.example.com/v1/contact-us/ca'},        {href: 'https://www.example.com/v1/contact-us/au'},        {href: 'https://www.example.com/v1/contact-us/us'},        {href: 'https://www.example.com/v1/dontcontact-us/us'}    ]};const regex = new RegExp('/contact\b', 'g');const correctRegex = new RegExp('/contact\b');const matchedSitesFailed = sites.links.filter(({href}) => regex.test(href));const matchedSitesSuccess = sites.links.filter(({href}) => new RegExp('/contact\b', 'g').test(href));const matchedSitesSuccess2 = sites.links.filter(({href}) => correctRegex.test(href));console.log('failed returns:', matchedSitesFailed.length);console.log('success returns:', matchedSitesSuccess.length);console.log('success returns 2:', matchedSitesSuccess2.length);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/368600.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号