You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让HTML页面将TXT文件解析为HTML代码?

将TXT文件解析为HTML展示的实现方案

前端纯JavaScript实现

1. 读取本地TXT文件

利用浏览器的FileReader API读取用户上传的TXT文件:

const fileInput = document.getElementById('txtFileInput');
fileInput.addEventListener('change', (e) => {
  const file = e.target.files[0];
  if (!file || file.type !== 'text/plain') {
    alert('请选择有效的TXT文件');
    return;
  }
  const reader = new FileReader();
  reader.onload = handleTxtContent;
  reader.readAsText(file);
});

2. 解析内容并转为HTML

根据TXT内容的格式规则,将文本转换为HTML结构。以下是基础示例:

function handleTxtContent(e) {
  const txtContent = e.target.result;
  // 规则:连续换行转段落,单个换行转换行标签
  const htmlContent = txtContent
    .replace(/\n\n/g, '</p><p>')
    .replace(/\n/g, '<br>');
  const finalHtml = `<div class="txt-output"><p>${htmlContent}</p></div>`;
  // 将生成的HTML插入页面容器
  document.getElementById('output').innerHTML = finalHtml;
}

配套HTML结构

<input type="file" id="txtFileInput" accept=".txt">
<div id="output"></div>

自定义格式解析扩展

如果你的TXT有特定标记(比如类Markdown规则),可以扩展解析逻辑:

function parseTxtToCustomHtml(txt) {
  const lines = txt.split('\n');
  let html = '';
  lines.forEach(line => {
    if (line.startsWith('# ')) {
      html += `<h1>${line.slice(2)}</h1>`;
    } else if (line.startsWith('## ')) {
      html += `<h2>${line.slice(3)}</h2>`;
    } else if (line.startsWith('- ')) {
      html += `<li>${line.slice(2)}</li>`;
    } else if (line.trim() === '') {
      html += '<br>';
    } else {
      html += `<p>${line}</p>`;
    }
  });
  return `<div class="custom-output">${html}</div>`;
}

内容的提问来源于stack exchange,提问作者Kazomix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 17:45:03