JavaScript读取本地TXT文件如何按行交替输出为标题和段落
解决方案
完全可以通过纯前端JavaScript的数组自动遍历实现需求,无需Node.js等运行环境,也不需要手动逐行处理。
你原有代码存在变量名错误:定义的FileReader实例名为test,但读取结果时写的是fl.result,会直接导致运行报错。
以下是可直接使用的完整代码:
<input type="file" name="files" id="inputfile" accept=".txt"> <div id="output"></div> <script type="text/javascript"> document.getElementById('inputfile').addEventListener('change', function() { // 未选择文件直接返回 if (!this.files[0]) return const reader = new FileReader() reader.onload = function() { const outputContainer = document.getElementById('output') // 清空上一次渲染的内容 outputContainer.innerHTML = '' // 按换行符拆分文本为行数组,过滤空行(不需要可删除.filter部分) const lines = reader.result.split(/\r?\n/).filter(line => line.trim()) // 遍历行数组自动生成对应元素 lines.forEach((line, index) => { let tag // 索引从0开始,偶数对应第1、3、5...行,渲染为标题 if (index % 2 === 0) { tag = document.createElement('h2') // 奇数对应第2、4、6...行,渲染为段落 } else { tag = document.createElement('p') } tag.textContent = line outputContainer.appendChild(tag) }) } // 显式指定UTF-8编码,避免中文乱码 reader.readAsText(this.files[0], 'UTF-8') }) </script>
自定义调整说明
- 标题默认用
h2标签,可根据需要改为h1/h3等其他标题标签 - 不需要过滤空行的话,把
.filter(line => line.trim())删除即可 - 不需要限制仅选择TXT文件的话,删除input标签的
accept=".txt"属性即可
内容的提问来源于stack exchange,提问作者OnionOfDoom
相关产品推荐
相关产品推荐

