简体   繁体   English

使用JS / Jquery .replace()替换text / html的多行块

[英]Using JS/Jquery .replace() to replace a multi line block of text/html

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. 我正在一个项目中,我需要从文件中提取HTML块,对提取的HTML进行调整,然后用更新的HTML替换文件中的HTML。 I am currently able to extract the HTML blocks that I want, but I am unable to replace them in the HTML file. 我目前能够提取所需的HTML块,但无法在HTML文件中替换它们。 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. 我现在主要在JS / Jquery中工作,我还没有写出文件,这不在此问题的范围内。

I have tried dumping the block of HTML into a variable and using it in the follow fashion: 我尝试将HTML块转储到变量中,并按照以下方式使用它:

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. 以上是我在其他SO帖子中找到的所有选项,但仍然无法进行替换。 You can view a basic breakdown in this Fiddle . 您可以在此Fiddle中查看基本分类。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks. 谢谢。

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 这是SO中的一个随机示例: 使用JS解析HTML字符串

Note that jQuery is optional. 请注意,jQuery是可选的。

What about just: 那么:

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

See jsFiddle 见jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM