javascript—在资源数组中找到合适的动态路径资源的最佳方法是什么?

nkkqxpd9  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(346)

我有以下资源数组,包括动态资源(“guides/:guideid/packages”)和当前URL(guides/guide007/packages):

const resources = ["guides", "guides/files", "guides/:guideId/packages"];
const currentURL = "guides/GUIDE007/packages";

const getResourceMatch = (resources, currentURL) => { return ... ?? }  

const resourceMatch = getResourceMatch(resources, currentURL);
console.log(resourceMatch) // guides/:guideId/packages

当currenturl匹配资源或资源格式时,在数组中查找该格式匹配的最佳方法是什么?

44u64gxh

44u64gxh1#

我将在前言中说,您可能应该尝试找到一个可以为您进行路由匹配的库。不过,这里有一个路由匹配实现,它可以将资源字符串转换为正则表达式来测试当前URL。

const resources = ["guides", "guides/files", "guides/:guideId/packages"];
const currentURL = "guides/GUIDE007/packages";

const getResourceMatch = (resources, currentURL) => {
  return resources.find(r => {
    const regexStr = '^' + r.replace(/(:\w+)/g,'[\\w-]+') + '$';
    const regex = new RegExp(regexStr);
    return regex.test(currentURL);
  })
}  

const resourceMatch = getResourceMatch(resources, currentURL);
console.log(resourceMatch) // guides/:guideId/packages

相关问题