0

I am working on a project where I need to extract a block of HTML from a file, make adjustments to the extracted HTML, and then replace the HTML in the file with the updated HTML. I am currently able to extract the HTML blocks that I want, but I am unable to replace them in the HTML file. I have been working mainly in JS/Jquery right now, I haven't gotten to the writing the file out yet, that's not in the scope of this issue.

I have tried dumping the block of HTML into a variable and using it in the follow fashion:

var removeThis = containerCopy.find('.keepMe, #showAlerts').remove().end().html(); var changed = containerMarkup.replace("/"+removeThis+"/gm", "<div>Replaced</div>");

I have also tried with out the regex formatting.

var changed = containerMarkup.replace(removeThis, "<div>Replaced</div>");

I have tried using regex to replace white spaces & line breaks, and also to escape special characters in both the extracted block & the initial block. Then running the replace. This still didn't work.

The above were all options I found through other SO posts, but I am still unable to get the replace to work. You can view a basic breakdown in this Fiddle. Any help would be greatly appreciated.

Thanks.

Lisa-J
  • 109
  • 1
  • 7
  • 3
    [**TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ**](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – adeneo Mar 14 '14 at 13:19

2 Answers2

0

I strongly suggest using a parser to interpret your markup. This should make traversing and manipulating its contents much easier and safer than using regexps, etc.

Here is a random example from SO: Parse a HTML String with JS

Note that jQuery is optional.

Community
  • 1
  • 1
ne1410s
  • 6,864
  • 6
  • 55
  • 61
0

What about just:

$('body').children().not('.keepMe, #showAlerts').remove();

See jsFiddle

A. Wolff
  • 74,033
  • 9
  • 94
  • 155