December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 7 | Removing HTML Tags from Text with DOMParser() |
Imagine you’ve written a web scraper that collects news from the web. The text you grab may contain unwanted HTML elements, like <span>, <img>, <a>, etc.
What’s worse, it may contain injected JavaScript code that automatically gets executed once you put it on your website. What you need is a function that safely removes all unwanted elements from the text.
Use the parseFromString() method from the DOMParser() interface to parse the string. Once you parse the string, you can use the textContent property to get the text free from any extra HTML tags:
| | function stripHTML(html){ |
| | const doc = new DOMParser().parseFromString(html, ... |
Read now
Unlock full access