Home > Web Front-end > JS Tutorial > How to Efficiently Remove HTML Tags from Text Using Plain JavaScript?

How to Efficiently Remove HTML Tags from Text Using Plain JavaScript?

Linda Hamilton
Release: 2024-12-27 07:11:13
Original
590 people have browsed it

How to Efficiently Remove HTML Tags from Text Using Plain JavaScript?

Stripping HTML Tags from Text in Plain JavaScript

Stripping HTML tags from a string is a common task in web development. While there are libraries available for this purpose, it's possible to achieve this using plain JavaScript.

Using the Browser's DOM

If your code runs in a browser, the easiest approach is to let the browser handle the HTML parsing. This can be done by creating a temporary DOM element and setting its innerHTML property to the HTML string. The resulting textContent or innerText property will contain the text without HTML tags.

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

Caution: This method should be used with caution when processing untrusted input, such as user-generated content.

Using DOMParser

An alternative method is to use the DOMParser interface, which is available in modern browsers. This allows you to parse HTML strings without creating DOM elements.

function stripHtml(html) {
   const doc = new DOMParser().parseFromString(html, "text/html");
   return doc.body.textContent;
}
Copy after login

Regular Expressions

Regular expressions can also be used to strip HTML tags from a string, but this approach is generally less efficient and robust compared to the above methods.

function stripHtml(html) {
   return html.replace(/<.+?>/g, "");
}
Copy after login

Remember to consider the limitations and security implications of each method when choosing the appropriate solution for your use case.

The above is the detailed content of How to Efficiently Remove HTML Tags from Text Using Plain 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