javascript - 解析元素内容以创建 HTML 表格行

标签 javascript jquery regex

我正在尝试将以下格式的数据解析为 3 个字段。字段 1 是节号。字段 2 是下一节之前的章节号之后的标题。字段 3 是下一节编号之前的所有剩余数据(如果有的话)。

3.2.2 The contractor shall provide demonstrated understanding and application of systems engineering and configuration management principals and process, mission planning/scheduling along with experience in systems engineering and sustainment of existing baseline, effectively conduct face-to-face interaction with customers and other contractors to respond to requests for information, support to technical meetings, technical interchanges and enterprise working groups. The contractor shall work independently and represent the program at meetings and working groups with Government and associate contractors. The contractor will support customer needs and support the customer in developing them into Business/Technical Requirements and establishing scope and schedule parameters to execute projects. 3.2.3 Design and installation of network extensions and cabling to support continued space conversions, including materials for NSWCPD buildings including 4, 1000, 29, 77L/H, 87, etc.

我尝试过正则表达式和逐字符循环。只是想知道是否有更有效的方法。

String.prototype.lines = function() {
  return this.split(/\r*\n/);
}
String.prototype.lineCount = function() {
  return this.lines().length;
}

$("#btnSave").on('click', function() {
  var textToParse = $("#textToParse").html();
  var allTRsAndTDs = "";

  // use regex or loop to generate parsed example loop only
  var iNumLines = $("#textToParse").lines().length;

  for (i = 1; i < iNumLines; i++) {
    allTRsAndTDs += `<tr>
      <td class="pws-section-id">1.1.1</td>
      <td class="title">This is the main title</td>
      <td class="description">Here is the remaining description</td>
    </tr>`;
  }

  $("#tableParsedRows").html(allTRsAndTDs);
});
#textToParse { width: 100%; min-height: 120px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <textarea id="textToParse">
3.1 Task area 1: Network Operation and Maintenance Services
3.1.1 The contractor shall provide the necessary labor and material to provide operation and maintenance services for a RDT&E network that supports data,
voice, and video applications. The network employs Ethernet, optical, and wireless technologies. The services include operating, maintaining, securely
configuring, patching, troubleshooting and diagnostic testing of network equipment and network routing protocols to determine the cause of network
problems/failures and repairing those problems/failures in a timely manner. Troubleshooting and repair services are required on all the network equipment
which includes, but is not limited to, file servers, blade servers, communications servers, routers, bridges, switches, firewalls, Virtual Private Networks (VPN),
power supplies, modems, Uninterrupted Power Supply (UPSs), network interface cards, and cable plant (twisted pair and fiber). Approximately 2,000 devices
are connected and communicate on the network. Contractor shall:
· Troubleshoot - identify network issues based on a variety of tools / methods (e.g. packet captures, specific device (firewalls) connection logging, Cisco
CMC, Cisco FMC, monitoring tools, NAC, 802.1x, & ASDM)


3.2 Task Area 2: Engineering
3.2.1 The contractor shall provide engineering services to support the overall network architecture and data, voice, and video applications operating on the
network. Engineering services to include: review and analysis of application requirements; engineering planning and design assistance; equipment and
component recommendation, and screening for standards compliance; installation and testing support to include verification and validation; documentation
preparation /review/analysis; engineering-level monitoring of the network which includes such things as determining cause of slowed network traffic, predicting
bottlenecks in advance, resolving address conflicts, improve design to virtual LAN architecture to ensure performance and enforce Government provided
security controls.
3.2.2 The contractor shall provide demonstrated understanding and application of systems engineering and configuration management principals and process,
mission planning/scheduling along with experience in systems engineering and sustainment of existing baseline, effectively conduct face-to-face interaction
with customers and other contractors to respond to requests for information, support to technical meetings, technical interchanges and enterprise working
groups. The contractor shall work independently and represent the program at meetings and working groups with Government and associate contractors. The
contractor will support customer needs and support the customer in developing them into Business/Technical Requirements and establishing scope and schedule
parameters to execute projects.
3.2.3 Design and installation of network extensions and cabling to support continued space conversions, including materials for NSWCPD buildings including
4, 1000, 29, 77L/H, 87, etc.
3.2.4 Server/Desktop Administration – UNIX/Linux Administration and Zone D Cybersecurity Compliance. Tasks include the installation; configuration;
integration; user-registration; execution of file backups; troubleshooting and problem resolution for all Linux Systems.
3.2.5 Support architecture, design, development, utilization, authorization, maintenance of, and migration to Department of Navy authorized cloud system
providers where approved by management.
3.2.6 Gather requirements via a formalized approach for requirements (i.e., Cloud, collaborations tools, DevOps, network connectivity, high performance
computing, etc.)
3.2.7 Identify Department of Navy authorized offerings (NR&DE Cloud, DISA, Cloud, etc.)
  </textarea>
  <div class="text-center" style="margin-top:25px; margin-bottom:25px">
    <input type="submit" id="btnSave" value="Save" class="btn btn-primary btn-large" />
  </div>
</form>

最佳答案

更新:将sections数组重构为section对象数组而不是字符串。

您需要在缓冲区中存储一个临时部分。如果检测到新的部分,则将该部分保存在缓冲区中并初始化一个新的缓冲区。

扫描完所有行后,检查是否需要再次保存。然后根据您创建的部分构造行。

const sectionRegex = /^\d+(?:\.\d+)*[ \t]+\S.*$/m;
const titleRegex   = /^(\d+\.\d+) (.+)$/;
const topicRegex   = /(\d+\.\d+\.\d+) (.+)$/;

$('#btnSave').on('click', function() {
  var sections = [], buffer = null;

  $('#textToParse').val().split(/\r*\n/).forEach(line => {
    if (line.match(sectionRegex)) {
      if (buffer != null) {
        sections.push($.extend({}, buffer)); // Save the buffer (copy of)
      }
    
      var title = line.match(titleRegex);
      if (title) {
        buffer = { // Initialize a new buffer
          num : title[1],
          title   : title[2],
          description : []
        }
      } else {
        var topic = line.match(topicRegex);        
        if (topic) {
          buffer = { // Initialize a new buffer
            num : topic[1],
            title   : '',
            description : [ topic[2] ]
          }
        }
      }
    } else {
      buffer.description.push(line); // Add to the buffer
    }
  });
  
  if (buffer.description.length > 0) {
    sections.push(buffer); // Save the buffer
  }
  
  // Construct table rows (joined description lines with a line-break)
  $('#tableParsedRows').empty().append(sections.map(section => `<tr>
      <td class="pws-section-id">${section.num}</td>
      <td class="title">${section.title}</td>
      <td class="description">${section.description.join('<br>')}</td>
    </tr>`));
});
#textToParse { width: 100%; min-height: 120px; }

.result-table table,
.result-table td,
.result-table th {
  border: thin solid black;
}
.result-table {
  border-collapse: collapse;
  border-color: black;
  width: 100%;
  margin-top: 0.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea id="textToParse">
3.1 Task area 1: Network Operation and Maintenance Services
3.1.1 The contractor shall provide the necessary labor and material to provide operation and maintenance services for a RDT&E network that supports data,
voice, and video applications. The network employs Ethernet, optical, and wireless technologies. The services include operating, maintaining, securely
configuring, patching, troubleshooting and diagnostic testing of network equipment and network routing protocols to determine the cause of network
problems/failures and repairing those problems/failures in a timely manner. Troubleshooting and repair services are required on all the network equipment
which includes, but is not limited to, file servers, blade servers, communications servers, routers, bridges, switches, firewalls, Virtual Private Networks (VPN),
power supplies, modems, Uninterrupted Power Supply (UPSs), network interface cards, and cable plant (twisted pair and fiber). Approximately 2,000 devices
are connected and communicate on the network. Contractor shall:
· Troubleshoot - identify network issues based on a variety of tools / methods (e.g. packet captures, specific device (firewalls) connection logging, Cisco
CMC, Cisco FMC, monitoring tools, NAC, 802.1x, & ASDM)


3.2 Task Area 2: Engineering
3.2.1 The contractor shall provide engineering services to support the overall network architecture and data, voice, and video applications operating on the
network. Engineering services to include: review and analysis of application requirements; engineering planning and design assistance; equipment and
component recommendation, and screening for standards compliance; installation and testing support to include verification and validation; documentation
preparation /review/analysis; engineering-level monitoring of the network which includes such things as determining cause of slowed network traffic, predicting
bottlenecks in advance, resolving address conflicts, improve design to virtual LAN architecture to ensure performance and enforce Government provided
security controls.
3.2.2 The contractor shall provide demonstrated understanding and application of systems engineering and configuration management principals and process,
mission planning/scheduling along with experience in systems engineering and sustainment of existing baseline, effectively conduct face-to-face interaction
with customers and other contractors to respond to requests for information, support to technical meetings, technical interchanges and enterprise working
groups. The contractor shall work independently and represent the program at meetings and working groups with Government and associate contractors. The
contractor will support customer needs and support the customer in developing them into Business/Technical Requirements and establishing scope and schedule
parameters to execute projects.
3.2.3 Design and installation of network extensions and cabling to support continued space conversions, including materials for NSWCPD buildings including
4, 1000, 29, 77L/H, 87, etc.
3.2.4 Server/Desktop Administration – UNIX/Linux Administration and Zone D Cybersecurity Compliance. Tasks include the installation; configuration;
integration; user-registration; execution of file backups; troubleshooting and problem resolution for all Linux Systems.
3.2.5 Support architecture, design, development, utilization, authorization, maintenance of, and migration to Department of Navy authorized cloud system
providers where approved by management.
3.2.6 Gather requirements via a formalized approach for requirements (i.e., Cloud, collaborations tools, DevOps, network connectivity, high performance
computing, etc.)
3.2.7 Identify Department of Navy authorized offerings (NR&DE Cloud, DISA, Cloud, etc.)
</textarea>
<input type="button" id="btnSave" value="Save" class="btn btn-primary btn-large" />
<table class="result-table">
  <thead>
    <tr>
      <th>Section</th>
      <th>Title</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody id="tableParsedRows"></tbody>
</table>

关于javascript - 解析元素内容以创建 HTML 表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56856725/

相关文章:

javascript - 固定位置导航栏不起作用

javascript - 将文本输入值更新到段落中的问题

javascript - jQuery.Click 方法重新加载页面

javascript - 使表格中的所有单元格具有相同的宽度等于最宽的单元格宽度

jquery - 获取数组中的背景颜色?

Python 正则表达式添加到 url 的链接

python - 检查字符串是否与 python 中的模式匹配的最有效方法?

regex - 如何在 Scala 中删除两个特定字符之间的子字符串

javascript - 按索引位置替换单词

javascript - $index 不存在于 ng-repeat 中 - 答案在我原来的帖子中