RegExp(str,'gi'); 
如果我只想替换2次,3次或n次,该如何写

解决方案 »

  1.   


    var count = 0;
    function f2c(s,n) {
      var test = /(\d+(\.\d*)?)F\b/g;    // 初始化模式。
      return(s.replace
        (test,
          function($0,$1,$2) { 
            count < n ? return((($1-32) * 5/9) + "C") : return $1;
            count++;
          }
        )
      );
      document.write(f2c("Water freezes at 32F and boils at 212F. Water freezes at 32F and boils at 212F",3));
    }
      

  2.   


    var count = 0;
    function f2c(s,n) {
      var test = /(\d+(\.\d*)?)F\b/g;    // 初始化模式。
      return(s.replace
        (test,
          function($0,$1,$2) { 
            count < n ? return((($1-32) * 5/9) + "C") : return $1;
            count++;
          }
        )
      );
    }document.write(f2c("Water freezes at 32F and boils at 212F. Water freezes at 32F and boils at 212F",3));
      

  3.   

    str.replace(regexp, (function(){
    var limit = 3; // 替换次数
    return function(m){
    return 0 > --limit ? m : 'your replace';
    }
    })());
      

  4.   

    str.replace(regexp, (function(){
        var limit = 3; // 替换次数
        return function(m){ return 0 > --limit ? m : 'your replace'; }
     })());正解。
    js闭包应用。
      

  5.   

    来个怪的
    var s="123 123, ddd 123 ff 123 fff 123,123,123,123";
    function replace(source,strF,strR,n){
       var a=s.split(strF);
       s=a.slice(0,n+1).join(strR)+(a.length>n+1?strF:"")+a.slice(n+1).join(strF);
       return s;
    }alert(replace(s,123,"[]",5));