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

如何在JavaScript中按指定单词分割字符串并生成对应数组?

解决方案

首先明确你的需求:把目标字符串按两次“stop”相关标记分割成三个部分,每个部分存入单独数组。下面是具体实现步骤:

步骤1:预处理原字符串

原字符串包含大量换行和冗余空格,先整理成干净的单行格式,避免后续处理出错:

let texto = "Catherine was there Sitting under a laurel Looking \nat the coolness of the falling waters Suddenly a soldier passed \nby \nand made him stop. stop soldier, I want to ask you a question \nHaven't you seen my husband who went to war one day? I haven't \nseen her husband I don't even know who (how) he is My husband is \ntall and blond, as handsome as you are. And on the tip of the hat \nit has San Andres written And on the tip of his sword is written \nSan Andres";

// 替换所有换行为空格,合并连续空格为单个,最后去除首尾空格
texto = texto.replace(/\n/g, ' ').replace(/\s+/g, ' ').trim();

步骤2:用正则提取三个目标部分

观察你要的结果,三个部分的分界很明确:

  • 第一部分到第一个stop(包含stop)
  • 第二部分在stop soldier,之后、My husband is之前
  • 第三部分从My husband is到结尾

用正则捕获组可以直接提取这三个片段:

// 定义正则,精准匹配并捕获三个目标部分
const sectionRegex = /(.*?stop)\.\s*stop soldier,\s*(.*?)\s*My husband is\s*(.*)/;
const matched = texto.match(sectionRegex);

// 将捕获到的内容存入对应数组
let primerSeccion = [matched[1]];
let segundaSeccion = [matched[2]];
let terceraSeccion = ["My husband is " + matched[3]];

步骤3:验证结果

打印输出即可得到你期望的内容:

console.log(primerSeccion);
// 输出:["Catherine was there Sitting under a laurel Looking at the coolness of the falling waters Suddenly a soldier passed by and made him stop"]

console.log(segundaSeccion);
// 输出:["I want to ask you a question Haven't you seen my husband who went to war one day? I haven't seen her husband I don't even know who (how) he is"]

console.log(terceraSeccion);
// 输出:["My husband is tall and blond, as handsome as you are. And on the tip of the hat it has San Andres written And on the tip of his sword is written San Andres"]

你之前代码的问题说明

  1. for循环里用return完全错误,return会直接终止整个函数,且循环内没有任何实际分割逻辑
  2. texto[0,6]写法不对,取字符串子串应该用texto.slice(0,7)(索引从0开始,取前7个字符才是"Catherine")
  3. 仅判断字符串是否包含stop,没有针对分割规则做实际的片段提取操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:45:42