如何获取URLPattern中所有命名组的数组?
提取URLPattern中的所有命名组
要从URLPattern的路径模式里揪出所有命名组,比如给/path/example/:name/:age返回['name', 'age'],还得支持带可选值的模式(比如/users/:id/:tab(home|photos|bio)),直接用正则解析路径模式就行,不用依赖URLPattern的exec方法,能兼容所有符合规范的路径格式。
实现代码
function getNamedGroupsFromURLPattern(pattern) { // 不管传的是URLPattern实例还是直接的路径字符串,先拿到路径部分 const pathname = pattern instanceof URLPattern ? pattern.pathname : pattern; // 匹配所有":组名"格式的命名组,后面带括号可选值也不影响 const groupRegex = /:([a-zA-Z0-9_]+)(?:\([^)]+\))?/g; const groups = []; let match; while ((match = groupRegex.exec(pathname)) !== null) { groups.push(match[1]); } return groups; } // 测两个例子看看 console.log(getNamedGroupsFromURLPattern('/path/example/:name/:age')); // 输出: ['name', 'age'] console.log(getNamedGroupsFromURLPattern(new URLPattern('/users/:id/:tab(home|photos|bio)'))); // 输出: ['id', 'tab']
为啥之前的方法不行?
之前用exec传入带模式占位符的URL的路子不靠谱,因为URLPattern的exec是用来匹配实际请求URL的,不是模式字符串本身。当模式里有括号可选值这类复杂结构时,这种方法要么识别不了命名组,要么直接匹配失败。
内容的提问来源于stack exchange,提问作者ThomasReggi
相关产品推荐
相关产品推荐

