Home > database >  Filter a pattern in middle of a string of an array JAVASCRIPT
Filter a pattern in middle of a string of an array JAVASCRIPT

Time:12-13

I have an array, I want to filter out all the paths which are in form of /__/:__Id I am currently using .endsWith property but I want to make a generic code which recognizes the pattern and doesn't return paths in pattern of /routename**/:nameId**

const ROUTES = [
    {
        path: "/",
        
    },
    {
        path: "/faqs",
       
    },
    {
        path: "/contactus",
        
    },
    {
        path: "/pricing",
        
    },
    {
        path: "/products",
     
    },
    {
        path: "/careers/:jobId",
       
    },
    {
        path: "/careers",
        
    },
    {
        path: "/about-us",
        
    },
    {
        path: "/features",
       
    },
    {
        path: "/usecase/:usecaseId",

    },
]

const selectedRoutes = ROUTES.map( (item) => {
  if (item.path === "/")
    return "";
else
return item.path;
}).filter( (item) => { return !item.endsWith("Id")}); 

CodePudding user response:

const ROUTES = [
    {
        path: "/",
        
    },
    {
        path: "/faqs",
       
    },
    {
        path: "/contactus",
        
    },
    {
        path: "/pricing",
        
    },
    {
        path: "/products",
     
    },
    {
        path: "/careers/:jobId",
       
    },
    {
        path: "/careers",
        
    },
    {
        path: "/about-us",
        
    },
    {
        path: "/features",
       
    },
    {
        path: "/usecase/:usecaseId",

    },
]

const selectedRoutes = ROUTES.map( (item) => {
  if (item.path === "/")
    return "";
else
return item.path;
}).filter( (item) => { return !item.includes(":")}); 

console.log(selectedRoutes);

CodePudding user response:

How about using regular expressions (regexp)?

const ROUTES = [{
    path: "/",

  },
  {
    path: "/faqs",

  },
  {
    path: "/contactus",

  },
  {
    path: "/pricing",

  },
  {
    path: "/products",

  },
  {
    path: "/careers/:jobId",

  },
  {
    path: "/careers",

  },
  {
    path: "/about-us",

  },
  {
    path: "/features",

  },
  {
    path: "/usecase/:usecaseId",

  },
]

const re = new RegExp('/.*/:.*Id', 'i');

const selectedRoutes = ROUTES.map((item) => {
  if (item.path === "/")
    return "";
  else
    return item.path;
}).filter((item) => {
  return !item.match(re)
});

console.log(selectedRoutes);

  • Related