如果设置全局参数就是全部 否则是一个 如何是指定数目

解决方案 »

  1.   


    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);
      

  2.   

    指定个数没试过,你可以把要replace的元素截取出来嘛!
      

  3.   

    可以在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>
      

  4.   

    // 修改 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) );