[英]What is the best way to find the proper dynamic path resource into an array of resources?
I have the following Array of resources, including a dynamic resource ("guides/:guideId/packages") and a currentURL (guides/GUIDE007/packages):我有以下资源数组,包括一个动态资源(“guides/:guideId/packages”)和一个 currentURL(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
What can be the best way to find that format match into the array as the currentURL matches a resource or a resource format?当 currentURL 匹配资源或资源格式时,找到该格式匹配到数组中的最佳方法是什么?
I will preface this by saying you should probably try to find a library that can do route matching for you.我会先说您应该尝试找到一个可以为您进行路由匹配的库。 Nevertheless, here's a route matching implementation for you that turns your resource strings into regular expressions to test the currentURL against.
不过,这里有一个路由匹配实现,它将您的资源字符串转换为正则表达式以测试 currentURL。
const resources = ["guides", "guides/files", "guides/:guideId/packages", "guides/packages/:packageId"]; const currentURL1 = "guides/GUIDE007/packages"; const currentURL2 = "guides/packages/PKG007"; 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 resourceMatch1 = getResourceMatch(resources, currentURL1); const resourceMatch2 = getResourceMatch(resources, currentURL2); console.log(resourceMatch1) // guides/:guideId/packages console.log(resourceMatch2) // guides/packages/:packageId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.