需要ie6或firefox或支持javascript5.5的
<script>
var myConst ={
"Red" : 1,
"Blue" : 2,
"Green" : 3,
"Yellow" : 4,
"While" : 5
};str = "color:[Red];background-color:[Yellow];"str2 =str.replace(/\[(.+?)\]/g,function($0,$1){return eval("myConst."+$1);} );alert(str2);
</script>
<script>
var myConst ={
"Red" : 1,
"Blue" : 2,
"Green" : 3,
"Yellow" : 4,
"While" : 5
};str = "color:[Red];background-color:[Yellow];"str2 =str.replace(/\[(.+?)\]/g,function($0,$1){return eval("myConst."+$1);} );alert(str2);
</script>
有一个缺点,本来已经用js5.5了,怎么还用效率低下的古董用法eval呢?
str2 =str.replace(/\[(.+?)\]/g,function($0,$1){return myConst[$1];} ); 不就行了。有没有更酷的解决办法?明天晚上我就结贴了。
var myConst={
"Red" : 1,
"Blue" : 2,
"Green" : 3,
"Yellow" : 4,
"While" : 5
}str = "color:[Red];background-color:[Yellow];"
re = /\[([^\]]+)\]/;
while(re.test(str)) str = str.replace(re,myConst[RegExp.$1])
alert(str)
</script>
其实都一样,这个已经是最简单的了
str2 =str.replace(/\[(.+?)\]/g,function(){return myConst[arguments[1]]];} );其实你动动脑子也就出来了嘛~~!非的要问!
呵呵~~自己动手丰衣足食。