JavaScript中如何分割字符串并保留分隔符前的紧邻文本?
JavaScript字符串分割方案
现有字符串:
const inputString = 'Crew: CAP(X): Ches, Ben, FO: Smith, Matthew, FO(T,P): Singh, Sushant';
需要将其分割为指定格式的数组,要求保留每个职务块的完整内容:
[ 'Crew', 'CAP(X): Ches, Ben, ', 'FO: Smith, Matthew, ', 'FO(T,P): Singh, Sushant' ]
原代码的问题
你之前尝试的split(/(?<=: )/)只会在: 的后方分割,无法识别每个新职务的起始位置,导致分割结果不符合预期。
正确实现方法
方法1:先拆分首段再处理剩余内容
const inputString = 'Crew: CAP(X): Ches, Ben, FO: Smith, Matthew, FO(T,P): Singh, Sushant'; // 拆分出首段"Crew"和剩余内容 const [firstSegment, restContent] = inputString.split(/: /, 2); // 对剩余内容按「空格+职务标识:」的前置位置分割,同时去除多余空格 const restSegments = restContent.split(/(?=\s+[A-Z]+\(?[^)]*\):)/).map(seg => seg.trimStart()); // 合并结果 const result = [firstSegment, ...restSegments]; console.log(result);
方法2:使用正则匹配直接提取目标片段
const inputString = 'Crew: CAP(X): Ches, Ben, FO: Smith, Matthew, FO(T,P): Singh, Sushant'; // 正则匹配首段和所有职务块,匹配到结尾或下一个职务起始位置为止 const result = inputString.match(/Crew|(?:[A-Z]+\([^)]*\)|[A-Z]+):.*?(?=\s+(?:[A-Z]+\([^)]*\)|[A-Z]+):|$)/g); console.log(result);
两种方法都能得到符合要求的数组结果。
内容的提问来源于stack exchange,提问作者PilotPatel
相关产品推荐
相关产品推荐

