ES6 filter an array with Regex
Solution 1:
Firstly new RegExp('/\bcontact\b', 'g');
is equivalent to /\/@contact@/g
where the @
are backspace character (ASCII 08) ... clearly not what you want
So, you would do new RegExp('/\\bcontact\\b', 'g');
- this is equivalent to /\/\bcontact\b/g
However, the \\b
after /
is redundant
so ... down to /\/contact\b/g
Using string.match
here as regex.test
is misused. Below is the description
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);
The next problem is using the ONE regex multiple times in a regexp.test
with g
flag. With each call, it will look from the next indexOf
previous found substring and with consecutive calls on a same-type string, it basically will return true
, false
, true
, false
.
If you want to use regex.test
, then don't re-use the same regex unless you know the consequences of doing so or do not use g
flag (which here you do not need)
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);
Solution 2:
I realize that the question requests regex, but the sensible answer here is
someArray.filter(str => str.includes('contact'))
Solution 3:
You need to return the truthy / falsy result from filter
function.
const sites = {
links: [
{
href: 'http://www.some-site.com/contact-us',
},
{
href: 'http://www.some-site.com/about',
},
{
href: 'http://www.some-site.com/admin',
},
],
};
const fitered = sites.links.filter((link) => {
return link.href.split('/').some((part) => part.includes('contact'));
});
console.log(fitered);