Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中将字符串与通配符匹配_Javascript_String_Routes_Wildcard - Fatal编程技术网

如何在javascript中将字符串与通配符匹配

如何在javascript中将字符串与通配符匹配,javascript,string,routes,wildcard,Javascript,String,Routes,Wildcard,我正在尝试编写一个函数,用于检查路由数组中是否包含路由: const routes = ['/test', '/documentation/*'] function checkRoute(route) { if (routes.includes(route)) { console.log('Included!!') } else { console.log('Not included!') } } 我需要帮助的部分是如何处理通配符*——基本上,我希望包含任何带有

我正在尝试编写一个函数,用于检查路由数组中是否包含路由:

const routes = ['/test', '/documentation/*']

function checkRoute(route) {
  if (routes.includes(route)) {
    console.log('Included!!')
  } else { 
    console.log('Not included!')
  }
}
我需要帮助的部分是如何处理通配符
*
——基本上,我希望包含任何带有
/docs/
前缀的路由,例如:

/documentation/docs.json
/documentation/index.html

除了做一些非常混乱的字符串操作,我不知道如何实现这一点。任何帮助都将不胜感激

您可以使用正则表达式

const routes=['\\/test\\/*','\\/documentation\\/*']
功能检查路线(路线){
设regex=newregexp(route);
让matchedRoutes=routes.filter(route=>regex.test(route))
}
您可以使用正则表达式

const routes=['\\/test\\/*','\\/documentation\\/*']
功能检查路线(路线){
设regex=newregexp(route);
让matchedRoutes=routes.filter(route=>regex.test(route))

}
这里是一个简单形式的通配符匹配函数。使用它并支持所有类型的通配符比较不是一个坏主意:


这里是一个简单的通配符匹配函数形式。使用它并支持所有类型的通配符比较不是一个坏主意:


John应该将
'/documentation/*'
更改为
'/documentation/*'
,因为它是正则表达式,而不是通配符匹配。或者可能是
'^/documentation/*'
,因此它只从路由的根匹配。@Chris
*
在结尾不需要,除非您使用
$
@Chris锚定它,我想应该将它更改为
\\/documentation\/*
,以便使用RegExp正确创建regex
newregexp('\\/documentation\\/*')
返回
/\/documentation\/*/
谢谢!但是有没有一种方法可以使用我原来的
路由
数组
常量路由=['/test','/documentation/*']
?John应该将
'/documentation/*'
更改为
'/documentation/*'
,因为它是正则表达式,而不是通配符匹配。或者可能是
'^/documentation/*'
,因此它只从路由的根匹配。@Chris
*
在结尾不需要,除非您使用
$
@Chris锚定它,我想应该将它更改为
\\/documentation\/*
,以便使用RegExp正确创建regex
newregexp('\\/documentation\\/*')
返回
/\/documentation\/*/
谢谢!但是有没有一种方法可以使用我原来的
路由
数组
常量路由=['/test','/documentation/*']