Home >Web Front-end >JS Tutorial >How Can I Remove HTML Tags from Text Using JavaScript?

How Can I Remove HTML Tags from Text Using JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 22:32:14422browse

How Can I Remove HTML Tags from Text Using JavaScript?

Stripping HTML Tags from Text: A JavaScript Solution

Stripping HTML tags from text is often necessary for various web development tasks. This can be achieved using plain JavaScript, without the need for external libraries.

JavaScript Solution:

If executed within a browser, one can leverage the browser's built-in capabilities for HTML parsing:

function stripHtml(html) {
  let tmp = document.createElement("DIV");
  tmp.innerHTML = html;
  return tmp.textContent || tmp.innerText || "";
}

This code creates a temporary DIV element, into which the HTML is placed. The textContent or innerText property of this element provides the text content without HTML tags.

Note:

As mentioned by commentators, this method should be avoided if the source of the HTML is not controlled. In such cases, using the DOMParser, as suggested by Saba in the answer provided, is a more recommended approach.

The above is the detailed content of How Can I Remove HTML Tags from Text Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn