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;
}
这个程序看不明白
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
var route = '/{controller}/{action}/{id}',
url = '/home/index/2';
groupRE(route, url);
function groupRE(re, s){
var names = [], result = {}, cursor = 0;
//正则匹配{}里的东西 m是有大括号的 g1是大括号里的动系
re = re.replace(/\{([^}]+)\}/g, function(m, g1){
names.push(g1);
return '(.+)';
});
//re是/.+/.+/.+
re = new RegExp(re);
var tmp = re.exec(s);
//将re转换成正则后匹配s
if(tmp){
for(var i=1; i<tmp.length; i++){
//把匹配的值和name数组里的建立关系 其中name的值是key 新匹配的值是value
if(names[i-1]){
result[ names[i-1] ] = tmp[i];
}
}
}
return result;
}
</script>
</head><body>
</body>
</html>
* @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'}
*/
请看这段注释
如果参数为home/index/2
则返回{controller:'home', action:'index', id:'2'}
这段代码的意思是通过正则表达式指定参数格式,然后返回相应的json对象。