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);
指定个数没试过,你可以把要replace的元素截取出来嘛!
可以在replace函数里自己限制,如: <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);
<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>
(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) );