1

basically I need to be able to search for tags "<" and ">" within a <code> block and have them set as TEXT rather than HTML, so that I can display all tags and HTML on the page.

At the moment all tags are coming through as actual HTML on the page when I do a string replace using jQuery:

var text = $("#edit").val();
filter = text.replace(/</gi,"&lt;").replace(/>/gi,"&gt;");
$("#output").html(filter);

I cant change html() to text() because any HTML, OUTSIDE the block is fine. I'm basically looking for something very similar as to how this textbox / code tag idea works on stackoverflow.

Is there an easy way to do this using JavaScript / jQuery?

Thanks

Tim
  • 6,986
  • 8
  • 38
  • 57
  • 1
    I'm a bit confused. You replace all occurrences of `<` and `>` in `text` with the corresponding HTML entity. So you somehow make *every* tag in `text` literal. Why would you not use `$("#output").text(text)` then? There is no HTML tag left in `text` to be rendered. What I want to say is that the reason you give for not using `text()` does not make sense. Or am I missing something? – Felix Kling Mar 12 '11 at 19:07
  • Would not suggest using regular expressions to parse HTML at all- see this (famous!) post http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags JS is pretty good at parsing HTML ;) – dianovich Mar 12 '11 at 19:19

2 Answers2

1

I'd suggest parsing the HTML and using the text() method to display your code block. How about something like

var text = $($('#edit').val()); //create HTML object and parse as you would DOM
var code = text.find('code').html();
$('#output').text(code);

Obviously you will have to place everything before and after the code block into your output div as HTML.

Hope this helps.

dianovich
  • 2,288
  • 21
  • 34
-1

I think you better use PHP regex to extract code between code tags and display them in pre tags to strip out formats:

<?php
$var="blahblah<code>...</code>booboo";
$var=ereg_replace("<code>(.*?)</code>", "", $var);   
print "<pre>$var</pre>";
?>
ngduc
  • 1,415
  • 12
  • 17