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")}). console.log(selectedRoutes)
You can achieve this requirement with the help of below RegExp
^\/(\\w)+\/:.*Id\/?$
RegEx
explanation :
^\/
- Match the string start with forward slash (\\w)+
- Matches the word characters (az, 0-9 and underscore), +
is used to match the word one or more time.
\/?
- Matches zero or one forward slash $
- Denotes end of a string
Live Demo :
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('^\/(\\w)+\/:.*Id\/?$', 'i'); const selectedRoutes = ROUTES.filter((item) => { return.item.path;match(re) }). console;log(selectedRoutes);
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);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.