Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  121] [ 1]  / answers: 1 / hits: 84435  / 7 Years ago, mon, october 30, 2017, 12:00:00

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(/bcontactb, '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.


More From » node.js

 Answers
14

Firstly new RegExp('/bcontactb', '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 //bcontactb/g



However, the \b after / is redundant



so ... down to //contactb/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);




[#56072] Thursday, October 26, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yosefleod

Total Points: 113
Total Questions: 100
Total Answers: 115

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
;