如何正确替换<pre> Element

时间:2015-04-29 00:16:50

标签: javascript jquery xhtml

How can I use jQuery (or even plain JS) to parse a given string as HTML and then replace the contents of all <pre> elements in the generated DOM (without encoding/decoding the entities in it) and convert it back to a string?

for example, say I have the following HTML stored as a string:

<p>HTML block</p>
<pre>
<body>
    <h1>Hello World</h1>
    <p>Hi</p>
</body>
</pre>

and I would like to turn all \n characters into <br/>, so that the output string will be:

<p>HTML block</p>
<pre><br/><body><br/><h1>Hello World</h1><br/><p>Hi</p></br></body><br/></pre>

Note that <pre> elements can have anything in them, including other nested elements or scripts.

I tried using $.parseHTML() but for some reason it strips out certain nested elements (for example, <body> inside a <pre>)

1 个答案:

答案 0 :(得分:1)

我知道RegEx不是最好的,但我稍后会添加DOM解决方案假设string是您的字符串

string.replace(/(?:\<pre[\S\s]*?\>)([\S\s]*?)(?:\<\/pre\>)/, string.match(/(?:\<pre[\S\s]*?\>)([\S\s]*?)(?:\<\/pre\>)/)[1].replace(/\n/g, '<br/>'));

<小时/>

的DOMParser

var d = (new DOMParser).parseFromString(string, 'text/html');
d.getElementsByTagName('pre')[0].innerHTML = d.getElementsByTagName('pre')[0].innerHTML.replace(/\n/g, '<br/>');

ddocument类似,您可以将此元素放在DOM结构中。

要使其成为字符串,您可以执行以下操作:

var d = (new DOMParser).parseFromString(string, 'text/html'); d.getElementsByTagName('pre')[0].innerHTML.replace(/\n/g, '<br/>');
var newstring = d.body.innerHTML;

这将生成一个新变量newstring,这是您的结果字符串