HTML to Text Html tools
HTML Input
Text Output
Developer Guide
// Simple HTML to text conversion
function htmlToText(html) {
// Create a temporary element
const temp = document.createElement('div');
temp.innerHTML = html;
// Handle line breaks
temp.querySelectorAll('br').forEach(br => br.replaceWith('\n'));
temp.querySelectorAll('p, div, h1, h2, h3, h4, h5, h6').forEach(block => {
block.insertAdjacentText('afterend', '\n\n');
});
// Handle links
temp.querySelectorAll('a').forEach(link => {
const href = link.getAttribute('href');
if (href) {
link.textContent = `${link.textContent} [${href}]`;
}
});
// Get text content
return temp.textContent || temp.innerText || '';
}
// Using the API
async function convertWithAPI(html) {
const response = await fetch('/tools/html-to-text', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
html: html,
preserve_links: true,
preserve_breaks: true
})
});
const result = await response.json();
console.log('Converted text:', result.text);
console.log('Statistics:', result.stats);
}
<?php
// Using PHP DOMDocument
function htmlToText($html, $options = []) {
$dom = new DOMDocument();
@$dom->loadHTML($html);
// Remove scripts and styles
$remove = ['script', 'style'];
foreach ($remove as $tag) {
$elements = $dom->getElementsByTagName($tag);
while ($elements->length > 0) {
$elements->item(0)->parentNode->removeChild($elements->item(0));
}
}
// Get text content
$text = $dom->textContent;
// Clean up whitespace
$text = preg_replace('/\s+/', ' ', $text);
$text = trim($text);
return $text;
}
// Advanced conversion with options
function advancedHtmlToText($html, $preserveLinks = true) {
$dom = new DOMDocument();
@$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
if ($preserveLinks) {
// Process links
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
$href = $link->getAttribute('href');
if ($href) {
$text = $link->textContent;
$link->textContent = "$text [$href]";
}
}
}
// Process block elements
$blocks = ['p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
foreach ($blocks as $tag) {
$elements = $dom->getElementsByTagName($tag);
foreach ($elements as $element) {
$element->appendChild($dom->createTextNode("\n\n"));
}
}
return strip_tags($dom->saveHTML());
}
?>
from bs4 import BeautifulSoup
import requests
def html_to_text(html, preserve_links=True):
"""Convert HTML to plain text with options"""
soup = BeautifulSoup(html, 'html.parser')
# Remove script and style elements
for script in soup(['script', 'style']):
script.decompose()
# Handle links
if preserve_links:
for link in soup.find_all('a'):
href = link.get('href', '')
if href:
link.string = f"{link.get_text()} [{href}]"
# Handle line breaks
for br in soup.find_all('br'):
br.replace_with('\n')
# Get text
text = soup.get_text(separator='\n')
# Clean up
lines = [line.strip() for line in text.splitlines()]
text = '\n'.join(line for line in lines if line)
return text
# HTML to Markdown conversion
def html_to_markdown(html):
"""Convert HTML to Markdown format"""
import html2text
h = html2text.HTML2Text()
h.ignore_links = False
h.ignore_images = False
h.body_width = 0 # Don't wrap lines
return h.handle(html)
# Using the API
def convert_with_api(html_content):
response = requests.post('https://yourdomain.com/tools/html-to-text',
data={
'html': html_content,
'mode': 'standard',
'preserve_links': 'true',
'preserve_breaks': 'true'
}
)
result = response.json()
return result['text']
const cheerio = require('cheerio');
const TurndownService = require('turndown');
// HTML to Text
function htmlToText(html, options = {}) {
const $ = cheerio.load(html);
// Remove unwanted elements
$('script, style').remove();
// Handle links
if (options.preserveLinks) {
$('a').each((i, elem) => {
const $elem = $(elem);
const href = $elem.attr('href');
if (href) {
$elem.text(`${$elem.text()} [${href}]`);
}
});
}
// Handle images
if (options.preserveImages) {
$('img').each((i, elem) => {
const $elem = $(elem);
const alt = $elem.attr('alt') || 'Image';
$elem.replaceWith(`[${alt}]`);
});
}
// Handle lists
$('ul, ol').each((i, elem) => {
const $list = $(elem);
const isOrdered = elem.name === 'ol';
$list.find('li').each((index, li) => {
const $li = $(li);
const prefix = isOrdered ? `${index + 1}. ` : '• ';
$li.prepend(prefix);
});
});
// Get text
let text = $.text();
// Clean up whitespace
text = text.replace(/\n\s*\n/g, '\n\n');
text = text.trim();
return text;
}
// HTML to Markdown
function htmlToMarkdown(html) {
const turndownService = new TurndownService({
headingStyle: 'atx',
codeBlockStyle: 'fenced'
});
return turndownService.turndown(html);
}
// Express.js endpoint
app.post('/api/html-to-text', (req, res) => {
const { html, mode, ...options } = req.body;
try {
let result;
if (mode === 'markdown') {
result = htmlToMarkdown(html);
} else {
result = htmlToText(html, options);
}
res.json({
success: true,
text: result,
stats: {
wordCount: result.split(/\s+/).length,
charCount: result.length
}
});
} catch (error) {
res.status(400).json({
error: 'Conversion failed',
message: error.message
});
}
});
What is HTML to Text Conversion?
HTML to text conversion is the process of extracting plain text content from HTML markup. This tool removes HTML tags while preserving the readable content and structure of your document. Whether you're extracting content from web pages, cleaning up email HTML, or converting formatted content to plain text, our converter handles it all with precision.
Smart Formatting
Intelligently preserves document structure including paragraphs, headings, and lists while removing HTML markup.
Link Preservation
Keep important URLs visible in your text output. Links are converted to readable format with URLs displayed.
Markdown Support
Convert HTML directly to Markdown format, perfect for documentation, README files, and content management systems.
Batch Processing
Convert multiple HTML files at once. Perfect for processing entire websites or document collections.
How HTML to Text Conversion Works
Parse HTML Structure
Our converter analyzes the HTML document structure, identifying elements like paragraphs, headings, lists, and links.
Extract Content
Text content is extracted from HTML elements while removing tags, scripts, styles, and other non-visible elements.
Apply Formatting Rules
Based on your selected options, formatting is applied to maintain readability and document structure.
Output Clean Text
The final result is clean, readable plain text that preserves the original content's meaning and structure.
Use Cases and Benefits
Email Processing
Convert HTML emails to plain text for better compatibility, reduced file size, and spam score improvement. Essential for email marketing and transactional emails.
Web Scraping
Extract clean text content from web pages for data analysis, content aggregation, or search engine indexing. Remove unwanted HTML markup and scripts.
Document Conversion
Convert HTML documents to plain text for compatibility with older systems, text editors, or when HTML formatting isn't supported.
Accessibility
Create accessible text versions of HTML content for screen readers, text-to-speech systems, and users with disabilities.
SEO and Content Analysis
Extract text for keyword analysis, content auditing, and SEO optimization. Get clean text without HTML interference.
Version Control
Convert HTML to text or Markdown for better diff visibility in version control systems like Git.
Advanced Features Explained
Conversion Modes
Standard Text Mode
Converts HTML to plain text while preserving basic formatting like line breaks and paragraph spacing. Ideal for general content extraction.
Markdown Mode
Converts HTML to Markdown syntax, maintaining formatting with Markdown conventions. Perfect for documentation and content management.
Minimal Mode
Strips all formatting and returns pure text content. Best for data processing and when formatting isn't needed.
Preservation Options
- Preserve Links: Keeps URLs visible in format [Link Text](URL) or "Link Text [URL]"
- Preserve Images: Shows image alt text in place of images for context
- Preserve Line Breaks: Maintains original line breaks and paragraph structure
- Preserve Lists: Formats lists with bullets (•) or numbers
Common HTML to Text Examples
Basic HTML Conversion
HTML Input:
<h1>Welcome</h1>
<p>This is a <strong>paragraph</strong> with <em>formatting</em>.</p>
<ul>
<li>First item</li>
<li>Second item</li>
</ul>
Text Output:
Welcome
This is a paragraph with formatting.
• First item
• Second item
Link Preservation Example
HTML Input:
<p>Visit our <a href="https://example.com">website</a> for more info.</p>
Text Output:
Visit our website [https://example.com] for more info.
Frequently Asked Questions
What HTML elements are preserved during conversion?
By default, we preserve the text content from all visible HTML elements. Structure elements like headings, paragraphs, lists, and tables are converted to maintain readability. Scripts, styles, and comments are removed.
Can I convert HTML tables to text?
Yes, HTML tables are converted to a readable text format. Each row is displayed on a new line with cells separated by pipes (|) or tabs, depending on your settings.
How does Markdown conversion differ from plain text?
Markdown conversion preserves formatting using Markdown syntax. Headers become #, bold text uses **, links use [text](url) format, etc. This maintains formatting in a plain text format.
Is there a size limit for HTML conversion?
Our tool can handle large HTML documents up to 10MB. For larger files or batch processing, consider using our API or desktop tools.
Can I automate HTML to text conversion?
Yes, we provide API access for automated conversion. Check our developer documentation for integration examples in various programming languages.
Best Practices for HTML to Text Conversion
1. Choose the Right Mode
Select Standard mode for general use, Markdown for documentation, or Minimal for data processing. Each mode optimizes output for different use cases.
2. Configure Preservation Options
Enable link preservation for content with important URLs. Use image alt text preservation when images convey important information.
3. Clean HTML First
For best results, ensure your HTML is well-formed. Broken tags or malformed HTML may produce unexpected results.
4. Test Output Formatting
Preview your output and adjust settings as needed. Different content types may require different preservation options.
Start Converting HTML to Text
Ready to extract clean text from HTML? Our converter is fast, accurate, and free to use. No registration required.