Use case :
This is a Cypress E2E test coded with JS and I'm trying to apply a regex filter to this array (more than 100 values) to be able to ignore everything before /flux/sitemaps/
and catches only the .xml file names. my aim is to be able to compare pre-production and production sitemap URL contents.
One example of what I would like to achieve :
Before regex :
["https://xxxxxxxxx.com/flux/sitemaps/sitemap_cms_1.xml","https://xxxxxx.com/flux/sitemaps/sitemap_category_1.xml"]
After regex (test goal) :
["/flux/sitemaps/sitemap_cms_1.xml","/flux/sitemaps/sitemap_category_1.xml"]
Or
["sitemap_cms_1.xml","sitemap_category_1.xml"]
I've tried different regex rules but no success so far, any help is greatly appreciated.
CodePudding user response:
The regex would be /\/flux\/sitemaps\/.*/
for first match, or /\/flux\/sitemaps\/(.*)/
with capturing group (second match).
const sitemap = [
'https://xxxxxxxxx.com/flux/sitemaps/sitemap_cms_1.xml',
'https://xxxxxx.com/flux/sitemaps/sitemap_category_1.xml'
]
const expected1 = [
'/flux/sitemaps/sitemap_cms_1.xml',
'/flux/sitemaps/sitemap_category_1.xml'
]
cy.wrap(sitemap)
.then(sm => sm.map(url => url.match(/\/flux\/sitemaps\/.*/)[0]))
.then(console.log)
.should('deep.eq', expected1)
const expected2 = [
'sitemap_cms_1.xml',
'sitemap_category_1.xml'
]
cy.wrap(sitemap)
.then(sm => sm.map(url => url.match(/\/flux\/sitemaps\/(.*)/)[1]))
.then(console.log)
.should('deep.eq', expected2)
CodePudding user response:
You can use Array.map
to create a new array populated with the results of another function on the existing array. In this case, we'll use Array.split
to remove everything before /flux/sitemaps
, and then use string interpolation to add the /flux/sitemaps
back on.
const origArr = ["https://xxxxxxxxx.com/flux/sitemaps/sitemap_cms_1.xml","https://xxxxxx.com/flux/sitemaps/sitemap_category_1.xml"]
const newArr = origArr.map((x) => `/flux/sitemaps${x.split('/flux/sitemaps')[1]}`);