将div中特定内容替换为HTML结构化内容的实现需求
处理带行号的无换行错误文本,转换为HTML列表
需求场景
需要将div内一段包含动态行号的无换行错误信息,转换成<ul>包裹的<li>列表,移除行号前缀,每条错误对应一个列表项。
解决方案(JavaScript实现)
通过正则表达式匹配行号前缀,拆分错误信息后构建HTML列表结构,替换原div内容:
// 替换为你的目标div选择器 const errorContainer = document.querySelector('#error-container'); const rawErrorText = errorContainer.textContent; // 拆分每条错误(匹配"line 数字, col 数字:"前缀) const errorMessages = rawErrorText.split(/line \d+, col \d+: /).filter(msg => msg.trim()); // 生成列表HTML const listMarkup = `<ul>\n ${errorMessages.map(msg => `<li>${msg}</li>`).join('\n ')}\n</ul>`; // 更新div内容 errorContainer.innerHTML = listMarkup;
输入输出示例
原始输入文本
line 120, col 8: The relative URL 'Helloo' for attribute 'href' in tag 'a' is disallowed. (see undefined)line 136, col 16: The relative URL 'fasdf' for attribute 'href' in tag 'a' is disallowed. (see undefined)line 155, col 12: Missing URL for attribute 'action-xhr' in tag 'form'. (see https://amp.dev/documentation/components/amp-form)
转换后输出HTML
<ul> <li>The relative URL 'Helloo' for attribute 'href' in tag 'a' is disallowed. (see undefined)</li> <li>The relative URL 'fasdf' for attribute 'href' in tag 'a' is disallowed. (see undefined)</li> <li>Missing URL for attribute 'action-xhr' in tag 'form'. (see https://amp.dev/documentation/components/amp-form)</li> </ul>
关键说明
- 正则表达式
/line \d+, col \d+: /精准匹配行号前缀,确保拆分出纯错误内容 filter(msg => msg.trim())过滤拆分后可能出现的空字符串(文本以行号前缀开头时会产生)map和join组合快速生成格式化的列表项,保持代码简洁
内容的提问来源于stack exchange,提问作者Reddy
相关产品推荐
相关产品推荐

