Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : Close open HTML tags in a string

Tags:

javascript

I have a javascript string that has HTML code. I display it and I have attached a read more/less toggler based on the number of words. The problem is, when I shrink the HTML code, it might have open tags, for suppose

<p>A computer is a general purpose device that can be <b>programmed</b> to carry out a finite set of arithmetic or logical operations</p>

when shrinked becomes

<p>A computer is a general purpose device that can be <b>programmed...more</p>

Because of unclosed bold tag, the following data becomes bold.

I want a javascript solution to close the unclosed tags in a string. Any kind of help is highly appreciated. Thank you all in advance.

like image 628
Spoorthy Ravuri Avatar asked Feb 07 '13 10:02

Spoorthy Ravuri


1 Answers

Use this code

function fixHtml(html){
  var div = document.createElement('div');
  div.innerHTML=html
  return (div.innerHTML);
}

using

var fixed = fixHtml("<b>some text")

will return

 <b>some text</b>
like image 79
SBoys3.com Avatar answered Oct 01 '22 11:10

SBoys3.com