繁体   English   中英

在数组 JAVASCRIPT 的字符串中间过滤模式

[英]Filter a pattern in middle of a string of an array JAVASCRIPT

我有一个数组,我想过滤掉所有形式为/__/:__Id的路径。 我目前正在使用.endsWith属性,但我想制作一个识别模式的通用代码,并且不会以 /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)

您可以在以下RegExp的帮助下实现此要求

^\/(\\w)+\/:.*Id\/?$

RegEx解释

^\/ - 匹配以正斜杠开头的字符串
(\\w)+ - 匹配单词字符(az、0-9 和下划线), +用于匹配单词一次或多次。
\/? - 匹配零个或一个正斜杠
$ - 表示字符串的结尾

现场演示

 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);

使用正则表达式 (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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM