![](/img/trans.png)
[英]Manipulate and filter a large string with similar pattern in 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.