javascript - How To Properly Replace The Content of a <pre> Element -
how can use jquery (or plain js) parse given string html , replace contents of <pre> elements in generated dom (without encoding/decoding entities in it) , convert string?
for example, have following html stored string:
<p>html block</p> <pre> <body> <h1>hello world</h1> <p>hi</p> </body> </pre> and turn \n characters <br/>, output string be:
<p>html block</p> <pre><br/><body><br/><h1>hello world</h1><br/><p>hi</p></br></body><br/></pre> note <pre> elements can have in them, including other nested elements or scripts.
i tried using $.parsehtml() reason strips out nested elements (for example, <body> inside <pre>)
i know regex isn't best but i'll add dom solution later. assuming string 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/>'); d document , can place element in dom structure.
to make string, can do:
var d = (new domparser).parsefromstring(string, 'text/html'); d.getelementsbytagname('pre')[0].innerhtml.replace(/\n/g, '<br/>'); var newstring = d.body.innerhtml; this make new variable, newstring resulting string
Comments
Post a Comment