(function(){
function gsub(str,replaceObj,regexp){
regexp = regexp || /(?:#{(\w+)})/g;
return str.replace(regexp,function(all,$1){
return replaceObj[$1];
})
}
var str = '<%what%> may have gone, but there is a time of <%how%>,#{reserve}';
console.log('gsub结果:',gsub(str,{
what : 'Swallows',
how : 'return'
},/(?:<%(\w+)%>)/g))
})();
现在把gsub挂到String的原型上面
复制代码 代码如下:
String.prototype.gsub = function(replaceObj,regexp){
regexp = regexp || /(^|.)(?:(#{)(\w+)(}))/g;
return this.replace(regexp,function(all,$1,$2,$3,$4){
if($1 == '\\'){
return $2+$3+$4;
}
return $1 + replaceObj[$3] ;
})
}
var str = '<%what%> may have gone, but there is a time of <%how%>,\\<%how%>,#{how}';
var obj = {
what : 'Swallows',
how : 'return'
}
console.log('测试1:',str.gsub(obj,/(^|.)(?:(<%)(\w+)(%>))/g));
//Swallows may have gone, but there is a time of return,<%how%>,#{how}
console.log('测试2:',str.gsub(obj));
//<%what%> may have gone, but there is a time of <%how%>,\<%how%>,return
嘿嘿,貌似和Prototype中的gsub很像了,不过Prototype中的gsub复杂一些,原理也不一致,熟悉一下,待会再仔细分析Prototype中的gsub方法。
您可能感兴趣的文章: