如何使用JavaScript提取文本中指定行的下一行内容?
JavaScript提取指定行及下一行内容的解决方案
核心思路
把整个文本按换行分割成行数组,过滤空行后,通过遍历数组定位目标行,直接提取同行内容或下一行内容,比用indexOf+substring的方式更稳定灵活。
完整代码示例
假设输入文本存储在pmsg变量中:
// 按换行分割文本,过滤空行(兼容\n和\r\n换行符) const lines = pmsg.split(/\r?\n/).filter(line => line.trim() !== ''); let name = ''; let customerStatus = ''; // 遍历行数组提取目标内容 for (let i = 0; i < lines.length; i++) { const currentLine = lines[i].trim(); // 提取Name后的内容 if (currentLine.startsWith('Name: ')) { name = currentLine.substring('Name: '.length).trim(); } // 提取"Are you a current customer?"的下一行内容 else if (currentLine === 'Are you a current customer?') { // 确保下一行存在 if (i + 1 < lines.length) { customerStatus = lines[i + 1].trim(); // 按期望把Yes转为No(不需要反转可删除此行) customerStatus = customerStatus === 'Yes' ? 'No' : 'Yes'; } } } // 输出结果 console.log(name); console.log(customerStatus);
代码说明
- 分割文本为行数组:
split(/\r?\n/)兼容Windows和Unix系统的换行符,filter去掉空行,避免空内容干扰遍历。 - 提取同行内容:用
startsWith定位Name行,直接截取关键词后的部分,无需计算固定长度,适配不同长度的名字。 - 提取下一行内容:找到目标问题行后,通过数组索引
i+1直接获取下一行内容,确保不会因为文本长度变化出错。
替换原有代码的优势
- 避免了固定长度截取(如
+28)的硬编码问题,文本内容变化时无需修改代码。 - 直观处理多行内容,无需手动查找换行符的位置,逻辑更清晰。
内容的提问来源于stack exchange,提问作者Leonardo Urbiola
相关产品推荐
相关产品推荐

