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

提取HTML简单列表项并生成[name, type]格式的二维数组

解决方案:将HTML列表转换为指定二维数组

没问题,我来帮你快速实现这个需求!要把你提供的HTML列表转换成[["test1", "hi"], ["test2", "bye"], ["test3", "hello"]]这样的二维数组,用原生JavaScript就可以轻松搞定,下面是两种可靠的实现方案:

首先先确认你的源HTML结构:

<ul id="testCaseList" class="list-group testCaseList"> 
  <li class="list-group-item justify-content-between" style="">test1 (hi)</li> 
  <li class="list-group-item justify-content-between" draggable="false" style="">test2 (bye)</li> 
  <li class="list-group-item justify-content-between" style="">test3 (hello)</li> 
</ul>

方案一:正则表达式匹配(推荐,适配格式小变动)

正则表达式可以灵活匹配文本中的名称和括号内的类型,即使文本前后有多余空格也能处理:

// 获取目标列表元素
const testCaseList = document.getElementById('testCaseList');
// 获取所有列表项
const listItems = testCaseList.querySelectorAll('li');
// 转换为目标二维数组
const result = Array.from(listItems).map(item => {
  // 清理文本首尾的多余空格
  const cleanText = item.textContent.trim();
  // 用正则匹配出名称和类型:匹配开头到左括号前的内容,以及括号内的内容
  const matchResult = cleanText.match(/^(.*?)\s*\((.*?)\)$/);
  // 返回处理后的子数组,这里做了简单的异常兼容(如果格式不匹配则返回空数组)
  return matchResult ? [matchResult[1].trim(), matchResult[2].trim()] : [];
});

console.log(result);
// 输出结果:[["test1", "hi"], ["test2", "bye"], ["test3", "hello"]]

方案二:字符串分割(适合格式完全固定的场景)

如果你的列表项文本格式完全固定(都是名称 (类型)的结构),用字符串分割的方式会更直观:

const testCaseList = document.getElementById('testCaseList');
const listItems = testCaseList.querySelectorAll('li');
const result = Array.from(listItems).map(item => {
  const cleanText = item.textContent.trim();
  // 找到左括号的位置
  const bracketPos = cleanText.indexOf('(');
  // 截取名称部分(左括号之前的内容)
  const name = cleanText.slice(0, bracketPos).trim();
  // 截取类型部分(左括号之后到右括号之前的内容)
  const type = cleanText.slice(bracketPos + 1, -1).trim();
  return [name, type];
});

console.log(result);
// 同样得到目标输出

两种方案都能达到你的需求,你可以根据实际场景选择:如果列表项文本可能有格式小变动(比如名称和括号之间有多个空格),优先用正则方案;如果格式完全固定,字符串分割的代码更易懂。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:50:13