2

I am not sure how practical this question is , but what i am trying to do is find html inside a string and then append pre tags to it using jquery. let say i have a variable with following string.

var string = "Some normal text <html><body><div> This is the html </div> </body></html>";

Html inside the string is dynamic and can contain any tags , what i want is to find the starting and ending of html and append,prepend pre tags accordingly.

Thanks

user963725
  • 121
  • 1
  • 2
  • 9
  • do you mean an entire html document or html fragments ? – krystan honour Mar 24 '12 at 11:34
  • lots of people will post regex examples,but I can tell you from experience these get complex very quickly, unless these are well known fragment structures you are going to tie yourself up in knots, see http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags for ideas, personally i'd try the regex route ONLY on well known structures not for random fragments that say a cms may have put there (which is what this is usually from) – krystan honour Mar 24 '12 at 12:01

3 Answers3

1

The following code does pretty much what you want, however it does not allow html, body tags etc. But those are not allowed in pre tags anyway.

var string = "Some normal text <html><body><div> This is the html </div> </body></html> more text<p>more html content</p>";
var holder = $('<div>').html(string);
holder.children().wrap('<pre>');

//Print result to console
console.log(holder.html());

Also a jsFiddle here: http://jsfiddle.net/evBCm/1/

Martin Hansen
  • 5,154
  • 3
  • 32
  • 53
0

Add the text to dynamic html tag e.g span or div and find desired node e.g

var string = "Some normal text <html><body><div> This is the html </div> </body></html>";
$("<span/>").html(string).find('div')
sakhunzai
  • 13,900
  • 23
  • 98
  • 159
  • i am not looking for div only , i want to grab the first instance where html is starting , it can be a div, p or any other tag – user963725 Mar 24 '12 at 11:39
-1

Apply bellow regix..

 var string = "Some normal text <html><body><div> This is the html </div> </body></html>";
 var iMatches = string.match("<html>(.*)</html>");
 var iHtml='<html>'+iMatches[1]+'</html>';
 alert(iHtml);
Hearaman
  • 8,466
  • 13
  • 41
  • 58