-2

I am acquiring the html in an html page. However I want to replace the entire contents of

<div id="fontsListing"></div>

with new contents.

I'm using the following but the regex here is messing up with my closing div tags.
How can I simply empty the contents of the fontsListing div
and enter in req.body.savedHtml?
Please note I can't use innerHtml as I need the actual javascript values to send to an api.

var newHtml = data.replace(/<div id="fontsListing">[\s\S]*?<\/div>/, "<div id=\"fontsListing\">" + req.body.savedHtml + "</div>");
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
Andrew Howard
  • 2,818
  • 5
  • 33
  • 59
  • Can you clarify why using innerhtml wouldnt work. To me it looks like youre trying to reimplement that method. – Achtung Jan 03 '21 at 19:01
  • Honestly you can't do this reliably with regex, as the end tag () could be part of an inner DIV. You need to parse the html and change in it there, then serialize back – ControlAltDel Jan 03 '21 at 19:03
  • @Achtung Because if I used innerhtml it would just alter the content in the dom of the html file. I need the actual html to save to an api, to then actually physically save the file. – Andrew Howard Jan 03 '21 at 19:03
  • Better to use a dom parser than regex – charlietfl Jan 03 '21 at 19:04

1 Answers1

-1

Found out the answer, (.*) is your friend, please see below:

var newHtml = data.replace(/<div id="fontsListing">(.*)<\/div>/g, "<div id=\"fontsListing\">" + req.body.savedHtml + "</div>");
Andrew Howard
  • 2,818
  • 5
  • 33
  • 59
  • Hey mate ! Is your question related to this one? https://stackoverflow.com/questions/7327056/appending-html-string-to-the-dom After I answered I became curious about what you are looking for? May be I have less information about it ? – Imran Rafiq Rather Jan 03 '21 at 19:25