Como remover tags HTML do texto (JavaScript, Python, Regex)

4 min de leitura

Remover tags HTML é uma das tarefas de processamento de texto mais comuns, seja limpando saídas de CMS, fazendo scraping web ou preparando texto para análise.

JavaScript

// Método DOM (mais seguro)
function stripHtml(html) {
  const doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent || '';
}

// Método regex (simples)
const text = html.replace(/<[^>]*>/g, '');

Python

from html.parser import HTMLParser
from io import StringIO

class MLStripper(HTMLParser):
    def __init__(self):
        super().__init__()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

# Ou simplesmente:
import re
re.sub(r'<[^>]*>', '', html)

Ferramenta online

Use nosso conversor para texto simples para remover HTML instantaneamente.