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

如何在JavaScript中按句号和逗号将段落拆分为数组?

如何用句号和逗号将文本拆分为可遍历的数组?

嗨,针对你的需求,我整理了一个简单直接的解决方案,结合你现有的代码就能快速实现:

核心思路

你需要用正则表达式匹配逗号和句号作为分隔符,同时处理分隔符后可能存在的空格,最后过滤掉拆分后可能出现的空字符串,就能得到干净的步骤数组了。

修改后的完整代码

return fetch(URI + 'api/brewing/1')
  .then((response) => response.json())
  .then((responseJson) => {
    var parsedResponse = JSON.parse(responseJson["data"][0]["steps"]);
    var stringData = JSON.stringify(parsedResponse);
    
    // 关键:拆分文本为数组
    const stepsArray = stringData.split(/[.,]\s*/).filter(step => step.trim() !== '');
    
    // 现在可以遍历数组做你需要的操作了
    stepsArray.forEach((step, index) => {
      console.log(`步骤 ${index + 1}: ${step}`);
    });
    
    return stepsArray; // 可返回数组供后续逻辑使用
  })
  .catch((error) => {
    console.error(error);
  });

代码解释

  • split(/[.,]\s*/):
    • [.,] 匹配任意一个目标分隔符(逗号或句号)
    • \s* 匹配分隔符后面的所有空白字符(空格、换行等),避免拆分出带前置空格的步骤
  • filter(step => step.trim() !== ''):
    过滤掉拆分后可能出现的空字符串(比如文本结尾有标点,或者连续标点的情况),保证数组里全是有效步骤

针对你的示例文本

用这段代码处理你给出的文本:

After soaking your filter in a warm water bath for at least five minutes, drop it into the bottom of your siphons top component, or hopper, and hook to the bottom of the hoppers glass tubing.,Fill your siphon bottom component.,Insert the hopper, filter and all.

最终会得到这样的数组:

[
  "After soaking your filter in a warm water bath for at least five minutes",
  "drop it into the bottom of your siphons top component",
  "or hopper",
  "and hook to the bottom of the hoppers glass tubing",
  "Fill your siphon bottom component",
  "Insert the hopper",
  "filter and all"
]

这样你就能轻松遍历每个步骤啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:26:26