Javascript的正则分组不支持命名,只好自己搞了一个。先把命名存入数组,然后匹配。
唉~~~有更好的解决方案么?
代码:
var route = '/{controller}/{action}/{id}', url = '/home/index/2'; groupRE(route, url); // ==> {controller:'home', action:'index', id:'2'} /* * @re: string, e.g.: '/{controller}/{action}/{id}' * @s: string to match, e.g.: 'home/index/2' * @return: dict, e.g.: {controller:'home', action:'index', id:'2'} */ function groupRE(re, s){ var names = [], result = {}, cursor = 0; re = re.replace(/\{([^}]+)\}/g, function(m, g1){ names.push(g1); return '(.+)'; }); re = new RegExp(re); var tmp = re.exec(s); if(tmp){ for(var i=1; i<tmp.length; i++){ if(names[i-1]){ result[ names[i-1] ] = tmp[i]; } } } return result; }