模板变量正则替换

varReplace : function (str,data) {
            var pattern =/\[(.)+?\]/gm;
            var match = str.match(pattern);
            if(match){
                for(var i=0; i<match.length; i++){
                    var key = match[i].replace(/([\[\]])*/gm, '');
                    if(undefined != data[key]){
                        str = str.replace(match[i],data[key]);
                    }
                }
            }
            return str;
        },

  例

var str = "/admin/department/edit/id/[id]/name/[name].html#treeEdit"
var data = {
            'id' : 123,
            "name" : 1233
        };

var url = varReplace(url,data);

console.log(url); /// 输出结果 admin/department/edit/id/123/name/1233.html#treeEdit

如果

var url="/admin/department/edit/id/%5Bid%5D/name/%5Bname%5D.html#treeEdit";

url转义了 可以通过decodeURI(url) 转义回来 在替换

相关推荐