1

I have a script to replace content of a document:

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

You can see i must write replace(/old1/gi, "new1").replace(/old2/gi, "new2").replace(/old3/gi, "new3").replace(/old4/gi, "new4").replace(/old5/gi, "new5"); 2 times.

How to make script works even just write above code once? like this:

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

Notice: old1,new1... are strings.

my notmypt
  • 55
  • 6

3 Answers3

4

You can match old, with lookahead for a number, and replace that with new:

const str = 'foo foo old1 bar bar old2 baz baz baz old3';
console.log(
  str.replace(/old(?=\d)/gi, 'new')
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

From your question basically you need to write once. You can simply do so by writing those steps into a function and calling that function.

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

Now if you titleEditor functionality is same as old1, old2 then you can write titleEditor as @CertainPermormance described

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

One more way you can do is adding method to String prototype

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

Hope it's helpful

Nilesh Soni
  • 405
  • 5
  • 12
0

Write a function that takes string argument and return modified string. 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"); }