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

如何用JavaScript提取关键词到空行或字符串结尾的多行子串?

提取多行文本中指定区域的内容并格式化输出

问题描述

现有JavaScript代码仅能处理单行文本的短语提取(维护名称、ID),无法适配多行场景。需要实现:提取文本中Colours affected之后到空行(或文本结尾)的所有颜色,以逗号分隔显示在同一文本框内。

示例输入文本结构:

Scheduled Maintenance 44445555666 - Multiple COLOURS Affected
Maintenance ID 444555666
Colours affected

Yellow
Blue
Black
red
purple

解决方案

通过添加状态标记来处理多行内容的收集,修改后的完整代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Information Extraction</title>
</head>
<body>

<textarea id="textarea" rows="20" cols="50">
Scheduled Maintenance 44445555666 - Multiple COLOURS Affected
Maintenance ID 444555666 
Colours affected

Yellow
Blue
Black
red
purple
</textarea>

<button onclick="extractInfo()">Extract Information</button>

<!-- 新增颜色显示区域 -->
<div>
  <label for="approvername">Scheduled Maintenance Name:</label>
  <input type="text" id="approvername" readonly>
</div>
<div>
  <label for="approveremail">Maintenance ID:</label>
  <input type="text" id="approveremail" readonly>
</div>
<div>
  <label for="affectedColours">Affected Colours:</label>
  <input type="text" id="affectedColours" readonly>
</div>

<script>
function extractInfo() {
  const text = document.getElementById('textarea').value;
  const lines = text.split('\n');
  let collectColours = false;
  const colours = [];

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim();
    
    // 提取维护名称
    if (line.includes('Scheduled Maintenance')) {
      const approverName = line.replace('Scheduled', '').trim();
      document.getElementById('approvername').value = approverName;
    }
    
    // 提取维护ID
    if (line.includes('Maintenance ID')) {
      const maintenanceId = line.replace(/.*Maintenance ID\D*(\d*).*/, '$1').trim();
      document.getElementById('approveremail').value = maintenanceId;
    }
    
    // 触发颜色收集状态
    if (line === 'Colours affected') {
      collectColours = true;
      continue;
    }
    
    // 收集非空行的颜色
    if (collectColours && line) {
      colours.push(line);
    }
    
    // 遇到空行且已收集到颜色,停止收集
    if (collectColours && !line && colours.length > 0) {
      collectColours = false;
    }
  }
  
  // 将颜色数组转为逗号分隔的字符串
  document.getElementById('affectedColours').value = colours.join(', ');
}
</script>

</body>
</html>

关键逻辑说明

  1. 状态标记:用collectColours变量标记是否进入颜色收集区域,当遍历到Colours affected行时开启该状态。
  2. 颜色收集:在收集状态下,仅将非空行的内容加入颜色数组,避免空行干扰。
  3. 终止条件:当遇到空行且已有颜色收集时,停止收集;若文本结尾没有空行,循环结束后自动终止。
  4. 格式化输出:用join(', ')将颜色数组转为逗号分隔的字符串,直接填充到对应输入框。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 21:17:21