user3569641
user3569641

Reputation: 922

Replacing URLs in html not working

I want to replace all the links in the html file but this does not working.

var fs = require('fs');

fs.readFile(__dirname + '/index.html', 'utf8', function(err, html){
 if(!err){
   html = html.replace('https://mysite1.github.io/',
'https://example.com/');
  console.log(html);
 }
 else{console.log(err);}

});

can u help me with this? I'm a bit new in nodejs/JavaScript

Upvotes: 1

Views: 43

Answers (1)

Talha Awan
Talha Awan

Reputation: 4619

replace replaces only the first instance. You need to use regular expression to replace all.

var fs = require('fs');

fs.readFile(__dirname + '/index.html', 'utf8', function(err, html){
 if(!err){
    var replaceLink = "https://mysite1.github.io/";
    var regex = new RegExp(replaceLink, "g");
    html = html.replace(regex, "https://example.com/");
    console.log(html);
 }
 else{console.log(err);}

});

Upvotes: 1

Related Questions