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

如何在JavaScript中从字符串列表提取子字符串(如Firstname)

提取字符串列表中Firstname对应内容的JavaScript方案

待处理的纯文本字符串列表:
Lead Code: LC123456789
Lead Type ID: 1
Firstname: Joe
Lastname: Bloggs
Addressline1: 123
Addressline2: NUMBER ROAD

方法一:使用split()实现

先遍历字符串数组定位包含Firstname:的行,再用: 分割字符串获取对应内容,逻辑直观:

const textLines = [
  'Lead Code: LC123456789',
  'Lead Type ID: 1',
  'Firstname: Joe',
  'Lastname: Bloggs',
  'Addressline1: 123',
  'Addressline2: NUMBER ROAD'
];

function getFirstname(lines) {
  const targetLine = lines.find(line => line.startsWith('Firstname:'));
  return targetLine ? targetLine.split(': ')[1] : null;
}

// 调用示例
console.log(getFirstname(textLines)); // 输出: Joe

方法二:简化版正则实现

你觉得正则复杂可能是想多了,这里可以用极简的正则匹配冒号后的内容,代码更紧凑:

function getFirstnameRegex(lines) {
  const targetLine = lines.find(line => line.includes('Firstname:'));
  if (!targetLine) return null;
  const [, firstname] = targetLine.match(/Firstname:\s*(.*)/) || [];
  return firstname;
}

// 调用示例
console.log(getFirstnameRegex(textLines)); // 输出: Joe

正则/Firstname:\s*(.*)/逻辑简单:\s*匹配冒号后可能存在的空格,(.*)捕获空格后到行尾的所有内容,直接提取即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:35:20