代码之家  ›  专栏  ›  技术社区  ›  my notmypt

在javascript中只使用一个方法多次

  •  1
  • my notmypt  · 技术社区  · 7 年前

    我有一个脚本来替换文档的内容:

    var mytitle = document.title ;
    document.title = mytitle
      .replace(/old1/gi, "new1")
      .replace(/old2/gi, "new2")
      .replace(/old3/gi, "new3")
      .replace(/old4/gi, "new4")
      .replace(/old5/gi, "new5"); 
    var mybody=document.body.innerHTML ;
    document.body.innerHTML=mybody
      .replace(/old1/gi, "new1")
      .replace(/old2/gi, "new2")
      .replace(/old3/gi, "new3")
      .replace(/old4/gi, "new4")
      .replace(/old5/gi, "new5"); 
    

    你可以看到我必须写 replace(/old1/gi, "new1").replace(/old2/gi, "new2").replace(/old3/gi, "new3").replace(/old4/gi, "new4").replace(/old5/gi, "new5"); 2次。

    如何使脚本工作,即使只是写上面的代码一次?这样地:

    var myreplace=replace(/old1/gi, "new1").replace(/old2/gi, "new2").replace(/old3/gi, "new3").replace(/old4/gi, "new4").replace(/old5/gi, "new5");
    var mytitle = document.title ;
    document.title = mytitle.myreplace;
    var mybody=document.body.innerHTML ;
    document.body.innerHTML=mybody.myreplace
    

    注意: old1 ,请 new1 ……是字符串。

    3 回复  |  直到 7 年前
        1
  •  1
  •   Nilesh Soni    7 年前

    var titleEditor = function(toEdit) {
        return toEdit.replace(/old1/gi, "new1")
                     .replace(/old2/gi, "new2")
                     .replace(/old3/gi, "new3")
                     .replace(/old4/gi, "new4")
                     .replace(/old5/gi, "new5");
        } 
        var mytitle = document.title ; 
        document.title = titleEditor(mytitle)
        var mybody=document.body.innerHTML;
        document.body.innerHTML= titleEditor(mybody);
    

    var titleEditor = function(toEdit){
         return toEdit.replace(/old(\d)/gi, 'new$1')
        }
    

    String.prototype.updateTitle = function(){
      return this.replace(/old(\d)/gi, 'new$1');
    }
    var mytitle = document.title ; 
    document.title = mytitle.updateTitle()
    var mybody=document.body.innerHTML;
    document.body.innerHTML= mybody.updateTitle();
    

        2
  •  4
  •   CertainPerformance    7 年前

    old new

    const str = 'foo foo old1 bar bar old2 baz baz baz old3';
    console.log(
      str.replace(/old(?=\d)/gi, 'new')
    );
        3
  •  0
  •   Binara Goonawardana    7 年前

    function replaceContent(string) { if (!string) return; return string .replace(/old1/gi, "new1") .replace(/old2/gi, "new2") .replace(/old3/gi, "new3") .replace(/old4/gi, "new4") .replace(/old5/gi, "new5"); }