I'm trying to filter an array that contains a bunch of urls. I need to return the urls that only contain the word "contact".
For example there is a link https://www.example.com/v1/contact-us/ca
This should be returned from the filter.
I tried this:
const regex = new RegExp("/\bcontact\b", 'g' ) sites.links.filter((val) => { console.log(regex.test(val.href)) })
It currently just sends back false through all the domains, when I know there is one domain that contains the word "contact".
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With