Approach 2 : Using .textContent property or .innerText property

The .textContent property returns the text content of the specified node and all its descendants. The .innerText property does the same thing as the .textContent property.

Example: In this example we will strip out HTML tag with above method.

javascript
// HTML tags contain text
let html = "<p>A Computer Science "
    + "Portal for Geeks</p>";
let div = document.createElement("div");
div.innerHTML = html;
let text = div.textContent || div.innerText || "";
console.log(text)

Output:

A Computer Science Portal for Geeks

How to remove HTML tags from a string using JavaScript ?

In JavaScript, there are several methods available to remove HTML tags from a string. One common approach is to utilize the replace() function along with regular expressions to strip out the tags. Additionally, you can leverage properties such as .textContent and .innerText from the HTML DOM to achieve the same result.

HTML tags come in two forms: opening tags and closing tags. Understanding this distinction is crucial when parsing and manipulating HTML content.

  • Opening tag: It starts with a ‘<‘, followed by an HTML keyword, and ends with a ‘>‘. <html>, <br>, <title> are some examples of HTML opening tags.
  • Closing tag: It starts with a ‘</‘, followed by an HTML keyword, and ends with a ‘>‘.</html>, </title> are examples of HTML closing tags.

Table of Content

  • Approach 1: Using replace() function
  • Approach 2 : Using .textContent property or .innerText property
  • Approach 3: Using DOMParser to Parse and Extract Text Content

Similar Reads

Approach 1: Using replace() function

The ‘<‘, ‘’, can be used to identify a word as an HTML tag in a string. The following examples show how to strip out HTML tags using replace() function and a regular expression, which identifies an HTML tag in the input string. A regular expression is a better way to find the HTML tags and remove them easily....

Approach 2 : Using .textContent property or .innerText property

The .textContent property returns the text content of the specified node and all its descendants. The .innerText property does the same thing as the .textContent property....

Approach 3: Using DOMParser to Parse and Extract Text Content

JavaScript’s DOMParser API provides a robust way to parse HTML strings into a DOM document, allowing for easy extraction of text content without HTML tags. By creating a DOMParser instance and then accessing the parsed document’s text content, we can effectively remove HTML tags from a string....

Contact Us