如何用JS处理textarea每行,仅对含(a)-(zzz)小写行删除指定annot标签
解决方案:处理textarea中特定行的标签清理
原代码存在的问题
- 字符串
replace()方法是返回新字符串,不会修改原变量,原代码未将替换结果重新赋值,导致修改无效 - 匹配条件过于局限,仅针对
(a) Definitions.,无法覆盖(a)至(zzz)的小写字母标识需求 - 处理完成后未将修改后的行重新合并,也没有赋值回textarea,导致页面看不到结果
修正后的完整代码
JavaScript 部分
function annotationWrapCleanups() { const textarea = document.querySelector('#textarea3'); let lines = textarea.value.split('\n'); // 匹配(a)到(zzz)的小写字母标识正则 const letterMarkerRegex = /\(([a-z]{1,3})\)/; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (line.trim() && letterMarkerRegex.test(line)) { // 替换开头的annot标签 let cleanedLine = line.replace('<annot:annotationLevel><annot:body>', ''); // 替换结尾的annot标签 cleanedLine = cleanedLine.replace('</annot:body></annot:annotationLevel>', ''); lines[i] = cleanedLine; } } // 将处理后的行重新合并并赋值回textarea textarea.value = lines.join('\n'); }
HTML 部分
<textarea class="main-textarea annotation-wrap" id="textarea3" rows="6"> <annot:annotationLevel><annot:body><p>“(a) Definitions. In this section:</p></annot:body></annot:annotationLevel> <annot:annotationLevel><annot:body><p>“(1) List of Material Interested Parties. The term “List of Material Interested Parties” means the List of Material Interested Parties established under subsection (c)(1).</p></annot:body></annot:annotationLevel> <annot:annotationLevel><annot:body><p>“(2) Oversight Board. The term “Oversight Board” has the meaning given the term in section 5 of PROMESA (48 U.S.C. 2104).</p></annot:body></annot:annotationLevel> <annot:annotationLevel><annot:body><p>“(b) Required Disclosure.</p></annot:body></annot:annotationLevel> </textarea> <button class="cleanup-btn" onclick="annotationWrapCleanups();">clean</button>
CSS 部分
.main-textarea { height: auto; width: 99%; padding: 8px; } .main-textarea:focus { outline: none; border: 1px solid #2196F3; } .cleanup-btn { padding: 10px 20px; margin-top: 10px; cursor: pointer; }
关键说明
- 正则表达式:
/\(([a-z]{1,3})\)/用于匹配括号内包含1-3个小写字母的标识,精准覆盖(a)到(zzz)的范围,同时不会匹配大写字母或罗马数字标识 - 字符串替换:每次
replace后将结果赋值给新变量(或直接覆盖原行),确保修改生效 - 结果回写:处理完成后通过
join('\n')将行重新合并,赋值回textarea,让页面显示处理后的内容
测试效果
点击clean按钮后,只有包含(a)、(b)的行会被清理annot标签,结果如下:
<p>“(a) Definitions. In this section:</p> <annot:annotationLevel><annot:body><p>“(1) List of Material Interested Parties. The term “List of Material Interested Parties” means the List of Material Interested Parties established under subsection (c)(1).</p></annot:body></annot:annotationLevel> <annot:annotationLevel><annot:body><p>“(2) Oversight Board. The term “Oversight Board” has the meaning given the term in section 5 of PROMESA (48 U.S.C. 2104).</p></annot:body></annot:annotationLevel> <p>“(b) Required Disclosure.</p>
内容的提问来源于stack exchange,提问作者ixcode
相关产品推荐
相关产品推荐

