Home >Web Front-end >JS Tutorial >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!