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 = < , > wrote script:
text = text.replace(new regexp("(?=(<pre>.*))<(?=(.*</pre>))","ig"),"<"); text = text.replace(new regexp("(?=(<pre>.*))>(?=(.*</pre>))","ig"),">"); i result:
<p>some text...<div class=example><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, '<').replace(/>/g, '>'); 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
Post a Comment