JavaScript中如何用正则对比对象内动态路径与静态字符串取值
路径模板匹配实现方案
实现思路
我们可以将包含{参数名}占位符的路径模板转换为正则表达式,用正则匹配传入的静态路径,匹配成功后返回对应取值即可。核心逻辑是把占位符替换为可匹配任意非/字符的正则片段,保证不会跨路径段匹配,符合常规接口路径的规则。
基础实现代码(JavaScript)
// 定义路径模板对象 const templateMap = { "/prodp/v1/engagemnt/{engID}/doc/{docID}":"roles_1", "/prodp/v1/engagemnt/{engID}/review/{reviewID}": "roles_2" } /** * 匹配静态路径对应的角色值 * @param {string} staticPath 待匹配的静态路径 * @param {object} templateMap 路径模板映射对象 * @returns {string|undefined} 匹配到的角色值,未匹配到返回undefined */ function getMatchedRole(staticPath, templateMap) { for (const templatePath of Object.keys(templateMap)) { // 将占位符替换为匹配任意非/字符的正则片段 const regExpPattern = templatePath.replace(/\{[^}]+\}/g, '[^/]+') // 加首尾限定符,避免部分匹配 const regExp = new RegExp(`^${regExpPattern}$`) if (regExp.test(staticPath)) { return templateMap[templatePath] } } return undefined } // 测试用例 const testPath = '/prodp/v1/engagemnt/1234/doc/doc_1234' console.log(getMatchedRole(testPath, templateMap)) // 输出:roles_1
进阶实现:同时提取占位符参数
如果需要同时获取路径中占位符对应的参数值,可以使用正则捕获组实现:
function getMatchedResult(staticPath, templateMap) { for (const templatePath of Object.keys(templateMap)) { const paramNames = [] // 提取占位符名称的同时生成带捕获组的正则 const regExpPattern = templatePath.replace(/\{([^}]+)\}/g, (_, paramName) => { paramNames.push(paramName) return '([^/]+)' }) const regExp = new RegExp(`^${regExpPattern}$`) const matchResult = staticPath.match(regExp) if (matchResult) { // 组装参数对象 const params = Object.fromEntries( paramNames.map((name, index) => [name, matchResult[index + 1]]) ) return { role: templateMap[templatePath], params: params } } } return undefined } // 测试用例 console.log(getMatchedResult(testPath, templateMap)) // 输出:{ role: 'roles_1', params: { engID: '1234', docID: 'doc_1234' } }
注意事项
如果存在多个模板可匹配同一路径的场景,建议提前对模板列表按「占位符数量升序、路径长度降序」排序后再遍历,保证更具体的路径优先匹配。
内容的提问来源于stack exchange,提问作者sharad jain
相关产品推荐
相关产品推荐

