首页 > 解决方案 > 在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"); 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... 是字符串。

标签: javascript

解决方案


您可以将old, 与前瞻数字匹配,并将其替换为new

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


推荐阅读