Методы JavaScript для извлечения обычного текста из строки HTML

Чтобы извлечь простой текст из строки HTML с помощью JavaScript, вы можете использовать несколько методов. Вот некоторые из них:

Метод 1: использование DOMParser и textContent

function extractPlainText(htmlString) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(htmlString, 'text/html');
  return doc.body.textContent || '';
}
const htmlString = '<h1>Hello, World!</h1><p>This is an example HTML string.</p>';
const plainText = extractPlainText(htmlString);
console.log(plainText); // Output: Hello, World! This is an example HTML string.

Метод 2: использование временного элемента и внутреннего текста

function extractPlainText(htmlString) {
  const tempElement = document.createElement('div');
  tempElement.innerHTML = htmlString;
  return tempElement.innerText || '';
}
const htmlString = '<h1>Hello, World!</h1><p>This is an example HTML string.</p>';
const plainText = extractPlainText(htmlString);
console.log(plainText); // Output: Hello, World! This is an example HTML string.

Метод 3. Использование регулярных выражений

function extractPlainText(htmlString) {
  return htmlString.replace(/<[^>]+>/g, '');
}
const htmlString = '<h1>Hello, World!</h1><p>This is an example HTML string.</p>';
const plainText = extractPlainText(htmlString);
console.log(plainText); // Output: Hello, World! This is an example HTML string.

Эти методы удалят все теги HTML и вернут текстовое содержимое из строки HTML.