87,904
社区成员
发帖
与我相关
我的任务
分享
<script type="text/javascript">
/* 替换两次ha为wa */
var s = 'hahahaha';
var l = 0;
var s2 = s.replace(/(ha)/ig,function(a,b){if(b&&l<2){l++;return 'Wa';}else{return b;}});
alert(s2);
</script>
String.prototype.replaceCount=function(reg,rep,count) {
var i=0,str=String(this);
while(str!=(str=str.replace(reg,rep)) && (++i<count));
return str;
};
var str="heillo ,this is my is dd hh is3 not my is is";
str=str.replaceCount(/(is)/,function($,$1) {
return String($1).toUpperCase();
},3)
alert(str);
// 修改 String.prototype.replace
(function () {
var method = String.prototype.replace
String.prototype.replace = function(regex, evaluator, frequency) {
if (!(frequency > 0)) return method.apply(this, arguments);
var count = 0;
return method.call(this, regex, function() {
return (count++ >= frequency) ? arguments[0] :
(evaluator instanceof Function) ? evaluator.apply(null, arguments) : evaluator;
});
};
})();
var s = "aaaaaaa";
WScript.Echo( s.replace(/a/g, "A") );
WScript.Echo( s.replace(/a/g, "A", 2) );
var i = 0;
WScript.Echo( s.replace(/a/g, function(){return ++i;}) );
i = 0;
WScript.Echo( s.replace(/a/g, function(){return ++i;}, 3) );