2017-04-07 70 views
1

我想替換html文件中的所有鏈接,但這不起作用。替換html中的URL不起作用

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

}); 

你能幫我嗎?我在nodejs/JavaScript中有點新東西

+0

'replace'語句之前'html'的值是什麼? – gurvinder372

+0

https://pastebin.com/V1VukHVB我將它添加到pastebin – user3569641

回答

1

replace只替換第一個實例。您需要使用正則表達式來替換全部。

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

});