In one of our previous post, I have explained how to convert word document into HTML using Javascript, in this article,we will be using Javascript to convert plain text into HTML element.
String to HTML using Javascript
You can simply convert html string into HTML data for user, by providing contents to div.innerHTML
in Javascript but it is better to use DOMParser for better output.
So, we can convert string into HTML using these simple steps:
- Grab plain text
- Check if browser support DOMParser, if yes, convert text into HTML else use fallback
- Append Converted HTML into Body.
Here is the Complete Javascript code to do this:
var support = (function () {
if (!window.DOMParser) return false;
var parser = new DOMParser();
try {
parser.parseFromString('x', 'text/html');
} catch(err) {
return false;
}
return true;
})();
var textToHTML= function (str) {
// check for DOMParser support
if (support) {
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body.innerHTML;
}
// Otherwise, create div and append HTML
var dom = document.createElement('div');
dom.innerHTML = str;
return dom;
};
document.getElementById("divMain").innerHTML= textToHTML('<h1>Hello</h1><p>Your HTML Contents are visible now</p>');
Here is the working fiddle
Convert Plain text into HTML Using jQuery
When using jQuery, you can directly using it's inbuilt function .html()
, here is the custom function
$.fn.toHtml=function(){
return $(this).html($(this).text())
}
Here is the complete sample HTML
<div id="div">
Here is the Converted :<span class="text"> Text</span> <br /><a href="javascript:void(0)">Link</a>
</div>
<br />
<input type="button" class="go" value="Convert to HTML ">
and jQuery code
$.fn.toHtml=function(){
return $(this).html($(this).text())
}
$('.go').click(function(){
$('#div').toHtml()
});
Working fiddle
You may also like to read:
Convert HTML to word using Javascript (With images)
Javascript Unit testing frameworks