在JavaScript中转换HTML为纯文本并保留链接、粗体与斜体格式
Preserving Bold/Italic in HTML-to-Plain-Text Conversion for Emails
Great question! Your existing function does a solid job handling line breaks and links—let’s adjust it to retain bold and italic formatting using markdown-style asterisks, which is clean and readable in email clients.
The Modified Function
Here’s how to update your htmlToText function to preserve bold (<b>, <strong>) and italic (<i>, <em>) styles:
function htmlToText(html){ // 移除代码换行符和制表符 html = html.replace(/\n/g, ""); html = html.replace(/\t/g, ""); // 保留粗体格式:替换<b>/<strong>为**...** html = html.replace(/<(b|strong)[^>]*>(.*?)<\/\1>/gi, '**$2**'); // 保留斜体格式:替换<i>/<em>为*...* html = html.replace(/<(i|em)[^>]*>(.*?)<\/\1>/gi, '*$2*'); // 保留HTML换行和制表符 html = html.replace(/<\/td>/g, "\t"); html = html.replace(/<\/table>/g, "\n"); html = html.replace(/<\/tr>/g, "\n"); html = html.replace(/<\/p>/g, "\n"); html = html.replace(/<\/div>/g, "\n"); html = html.replace(/<\/h[1-6]>/g, "\n"); // 修正原h标签正则,匹配合法的h1-h6闭合标签 html = html.replace(/<br>/g, "\n"); html = html.replace(/<br( )*\/>/g, "\n"); // 处理链接格式 html = html.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 (Link->$1) "); // 将HTML解析为文本 var dom = (new DOMParser()).parseFromString('<!doctype html><body>' + html, 'text/html'); return dom.body.textContent; }
Key Changes Explained
- Bold/Italic Replacement: We added two regex patterns that match
<b>/<strong>and<i>/<em>tags (including any extra attributes like classes or styles) and replace them with markdown-style**and*respectively. The\1in the closing tag ensures we match the exact same opening tag (e.g.,<strong>closes with</strong>, not</b>). - Fixed Heading Tag Regex: Your original
<\/h>pattern would only match invalid</h>tags—we updated it to<\/h[1-6]>to properly handle valid closing heading tags from</h1>to</h6>.
Test Example
For your sample content:
这是粗体文本。这是普通文本。这是斜体文本。这是一个链接。
The function will output:
**这是粗体文本。**这是普通文本。*这是斜体文本。* 这是一个链接。 (Link->https://example.com)
This format keeps your original formatting intent intact while remaining easy to read in plain-text emails.
内容的提问来源于stack exchange,提问作者petoma
相关产品推荐
相关产品推荐

