Strip HTML

The problem with Strip HTML

In this blog, we will learn how we can strip HTML text from JavaScript code. Although there are many ways to achieve the same we will focus on the easy approaches to do the same. 

 

 

Solution

The first approach focuses on stripping the text if the user is working on a browser. The code for the same is shown below:

 

 

function stripHtml(html)

{

let tmp = document.createElement("DIV");

tmp.innerHTML = html;

return tmp.textContent || tmp.innerText || "";

}

 

 

One of the best practices is that one should not control the source of the HTML codes. Another option is to run the below code to achieve the same:

 

 

myString.replace(/<[^>]*>?/gm, '');

 

 

One of the most simple ways to retrieve all the text from an HTML string is also given here. 

 

 

jQuery(html).text();

 

 

In addition the jQuery, the method will return an empty string if there is no HTML in the string (for example, if you are trying to delete HTML from a form field). One can also use the below code instead of the above one.

 

 

jQuery('<p>' + html + '</p>').text();

 

 

Use an alternative method if you think an attacker might be able to influence the value of the HTML, as it has been noted in the comments that this solution may occasionally run javascript that is included within HTML.

 

 

Also Read: What is UnboundLocalError and reason for it

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *