首先,
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.testwith
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);


