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

f0brbegy  于 2022-12-17  发布在  Java
关注(0)|答案(3)|浏览(206)

我有一个数组,我想过滤掉所有/__/:__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)
m4pnthwp

m4pnthwp1#

您可以借助下面的RegExp实现此要求

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

RegEx说明**:**
^\/-匹配以正斜杠开头的字符串
(\\w)+-匹配单词字符(a-z、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);
sdnqo3pr

sdnqo3pr2#

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

0ejtzxu13#

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

相关问题