需求:实现满足字符数与标点双条件的文本换行功能
文本清理+智能换行实现方案
核心需求回顾
- 先清理文本:移除多余空格、数字、换行符,统一格式
- 智能换行规则:
- 换行需满足至少达到指定字符数(示例阈值设为50)
- 优先以逗号
,或句号。作为换行位置 - 仅当字符数接近设定值时才换行,避免频繁换行
完整实现代码
<script> function printText() { var inputValue = document.getElementById("paste-text").value; // 设定每行最小字符阈值,可根据需求修改 const lineLength = 50; // 文本清理函数 function cleanText() { let cleaned = inputValue .replace(/(\r\n|\n|\r)/g, ' ') // 移除所有换行符 .replace(/[0-9]/g, ' ') // 移除所有数字 .replace(/\s+/g, ' ') // 合并所有连续空格为单个空格 .trim(); // 移除首尾空格 return cleaned; } // 智能换行函数 function wrapText(text) { if (!text) return ''; let result = []; let currentLine = ''; let currentLength = 0; // 按标点分割成带标点的短语,过滤空值 const phrases = text.split(/([,。])/).filter(Boolean); for (let i = 0; i < phrases.length; i++) { const phrase = phrases[i]; const phraseLength = phrase.length; // 当前行加上短语后接近阈值(预留5字符缓冲),触发换行 if (currentLength + phraseLength >= lineLength - 5 && currentLength > 0) { result.push(currentLine.trim()); currentLine = phrase; currentLength = phraseLength; } else { currentLine += phrase; currentLength += phraseLength; } } // 添加最后一行内容 if (currentLine) { result.push(currentLine.trim()); } return result.join('\n'); } if (inputValue.length > 0) { const cleanedText = cleanText(); const formattedText = wrapText(cleanedText); document.getElementById("text-output").innerText = formattedText; document.getElementById("edit-text-output").classList.add("showEdited"); } } </script> <section> <div class="edit-text-container"> <div class="edit-text-input"> <div class="edit-text-paste"> <h3>粘贴文本</h3> <div class="edit-text-input-area"> <textarea name="paste-text" id="paste-text" rows="6" placeholder="在此粘贴文本"></textarea> </div> <input type="submit" value="清理并格式化" onclick="printText()"> </div> </div> <div id="edit-text-output"> <h3>处理后的文本</h3> <div class="edit-text-output-area"> <textarea readonly id="text-output" rows="6"></textarea> </div> </div> </div> </section> <style> textarea { margin:0; width:100%; padding:16px; box-sizing: border-box; /* 修复padding导致的宽度溢出问题 */ } #edit-text-output { height:0px; overflow:hidden; opacity:0; transition: all 0.5s; margin-top: 16px; } .showEdited { height:185px!important; opacity:1!important; } .edit-text-container { display:flex; justify-content:center; gap: 24px; text-align:center; max-width: 1200px; margin: 0 auto; } .edit-text-input, .edit-text-output-area { flex:1; min-width: 300px; } input[type=submit] { margin-top:16px; padding: 8px 16px; cursor: pointer; } </style>
关键逻辑说明
文本清理优化:
- 用
\s+替代多次空格替换,一次合并所有连续空格,代码更简洁高效 - 保留核心清理规则:移除换行、数字、多余空格
- 用
智能换行逻辑:
- 将文本按逗号、句号分割成带标点的短语,确保换行始终在标点之后
- 设置
lineLength - 5的触发缓冲,只有当当前行加上下一个短语的长度接近设定阈值时才换行,避免频繁换行 - 遍历短语逐步拼接,达到阈值时将当前行存入结果,重新开始新行
示例效果(阈值设为50)
输入清理后文本:敏捷的棕色狐狸跳过懒狗,直到那只狗,睡着了。敏捷的棕色狐狸跳过另一只懒狗,然后在草地上休息。
输出结果:
敏捷的棕色狐狸跳过懒狗,直到那只狗,睡着了。 敏捷的棕色狐狸跳过另一只懒狗,然后在草地上休息。
内容的提问来源于stack exchange,提问作者Brendon
相关产品推荐
相关产品推荐

