html - Regular expressions in javascript and replace method -


i have string var:

some text...<div class=example><pre><ul><li>item</li></ul></pre><div class=showexample></div></div>some text... 

i want replace < , > chars in pre tag html entity = &lt; , &gt; wrote script:

text = text.replace(new regexp("(?=(<pre>.*))<(?=(.*</pre>))","ig"),"&lt;"); text = text.replace(new regexp("(?=(<pre>.*))>(?=(.*</pre>))","ig"),"&gt;"); 

i result:

<p>some text...<div class=example>&lt;pre><ul><li>item</li></ul></pre><div class=showexample></div></div>some text...</p> 

why???

it's because of first lookahead: (?=(<pre>.*)). when cursor of regex right before <pre>, matches since have < , there <pre> ahead.

you intended have lookbehind there (?<= ... ) instead, javascript doesn't support them.

i'm not familiar js, might easier first extract stuff within <pre> tags:

match = text.match(/<pre>(.*?)<\/pre>/)[1]; 

then replace need replace in little group:

match = match.replace(/</g, '&lt;').replace(/>/g, '&gt;'); 

then replace original:

text = text.replace(/<pre>.*?<\/pre>/g, '<pre>'+match+'</pre>'); 

as said before, i'm not familiar js, guess can run loop replace multiple texts within <pre> tags.

for example, here's fiddle.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -