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:
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 || ""; }
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!