在javascript中多次使用一种方法

时间:2018-07-05 04:09:06

标签: javascript

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

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

即使只编写一次以上代码,如何使脚本正常工作?像这样:

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

注意:old1new1 ...是字符串。

3 个答案:

答案 0 :(得分:4)

您可以将old匹配,先行查找一个数字,然后将其替换为new

const str = 'foo foo old1 bar bar old2 baz baz baz old3';
console.log(
  str.replace(/old(?=\d)/gi, 'new')
);

答案 1 :(得分:1)

从您的问题开始,基本上您只需要写一次。您只需将这些步骤写入函数并调用该函数即可。

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

现在,如果titleEditor的功能与old1,old2相同,则可以将titleEditor编写为@CertainPermormance所述

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

另一种方法是将方法添加到String原型

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 :(得分:0)

编写一个接受字符串参数并返回修改后的字符串的函数。 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"); }

相关问题