0

I'm trying to create a tool that will allow me to quickly update several text strings in an html file. I'm doing this by searching for the contents of tags with specific ids and then replacing their text content. I've got much of it working but I'm not sure how to enable this to write multiple replacements into the file. As it is, it's simply running only the last of my replacements.

Here's what I have:

var fs = require('fs')
fs.readFile('sample.html', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }

  var title1 = "boogers"
  var text1 = "ronald mcdonald";

  var result = data.replace(/<div id="text1">(.*)<\/div>/g, '<div id="text1">' + text1 + '</div>'); 
  var result = data.replace(/<title>(.*)<\/title>/g, '<title>' + title1 + '</title>'); 
    fs.writeFile('sample.html', result, 'utf8', function (err) {
     if (err) return console.log(err);
  }); 
});

In the code above, it will replace the title's content but not the div tag's. I imagine this is a pretty basic fix but I'm new to node js and javascript. Thanks for any help.

2
  • Can you give a concrete example of the sample.html and the expected output from it? Commented Mar 6, 2019 at 21:10
  • The problem here because you are overriding the result Second line should be result = result.replace Commented Mar 6, 2019 at 21:12

2 Answers 2

3

You are "creating" variable result twice, and attributing the replacement over data twice. So, in the second attribution you loose the replacement done before. Try this:

fs.readFile('sample.html', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }

  var title1 = "boogers"
  var text1 = "ronald mcdonald";

  var result = data.replace(/<div id="text1">(.*)<\/div>/g, '<div id="text1">' + text1 + '</div>'); 
  result = result.replace(/<title>(.*)<\/title>/g, '<title>' + title1 + '</title>'); 
    fs.writeFile('sample.html', result, 'utf8', function (err) {
     if (err) return console.log(err);
  }); 
});
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! So is this line: result = result.replace(/<title>(.*)<\/title>/g, '<title>' + title1 + '</title>'); basically saying "set result to be the previously set contents (e.g. the replacement of the div tag) plus this new content (e.g. the replacement of the div tag)?
@WForbis Yes. Exactly.
-1

Simply use "//g" global method

var str = "aaabbcccasbbbb"; //main string
var repStr = "ss";  //replace string
var result = str.replace(/[ab]/g, repStr);  //result
console.log(result);

Result will be: sssssssssscccsssssssssss

1 Comment

This is not the point, we want to do it from a file, not from a string...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.