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

How Can I Remove HTML Tags from Text Using Pure JavaScript?

Susan Sarandon
Release: 2024-12-17 02:09:24
Original
898 people have browsed it

How Can I Remove HTML Tags from Text Using Pure JavaScript?

Stripping HTML Tags from Text with Pure JavaScript

Stripping HTML tags from text can be a common task in web development, for example, when parsing content from untrusted sources or converting HTML to plain text. Here's how to do it using plain JavaScript, without relying on external libraries:

Using the DOM to Remove Tags

If you're working in a browser environment, the most efficient method is to leverage the browser's built-in HTML parsing capabilities:

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

Note: Security Considerations

As noted in the comments, this approach should be used with caution when dealing with untrusted HTML, such as user input. Malicious code could be injected through tags, so it's recommended to sanitize the HTML first before stripping tags.

For handling untrusted HTML, consider using a more secure method like DOMParser, as suggested in an alternative answer by Saba.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template