简体   繁体   English

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

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

I have an array, I want to filter out all the paths which are in form of /__/:__Id .我有一个数组,我想过滤掉所有形式为/__/:__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**我目前正在使用.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)

You can achieve this requirement with the help of below RegExp您可以在以下RegExp的帮助下实现此要求

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

RegEx explanation : RegEx解释

^\/ - 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. (\\w)+ - 匹配单词字符(az、0-9 和下划线), +用于匹配单词一次或多次。
\/? - 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)?使用正则表达式 (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