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

如何在JavaScript/AngularJS中拆分单索引数组内的分步字符串

JavaScript拆分带编号步骤字符串为数组的实现方案

嘿,这个场景我之前碰到过,用正则表达式就能轻松搞定!先明确需求:

现有单索引数组:["1. Get into car.2. Buckle seat belt.3. Start Ignition"],需要将其中的字符串按步骤编号拆分,最终得到数组:["1. Get into car.", "2. Buckle seat belt.", "3. Start Ignition"]

核心实现代码

直接上可运行的JavaScript代码:

// 原始输入数组
const originalArray = ["1. Get into car.2. Buckle seat belt.3. Start Ignition"];
// 取出数组中唯一的字符串元素
const combinedSteps = originalArray[0];
// 用正则拆分并过滤空内容
const splitSteps = combinedSteps.split(/(?=\d+\.)/).filter(step => step.trim() !== '');

console.log(splitSteps);
// 输出结果:["1. Get into car.", "2. Buckle seat belt.", "3. Start Ignition"]

代码解释

  • 正则/(?=\d+\.)/是正向预查,它会匹配“一个或多个数字(\d+)紧跟一个点号(\.)”的位置,但不会消耗这些字符,这样拆分出来的每个元素都会完整保留步骤编号。
  • 用filter(step => step.trim() !== '')是为了避免拆分后出现空字符串(虽然这个场景下大概率不会有,但能让代码更健壮)。

AngularJS中的适配写法

如果是在AngularJS项目里使用,可以直接在控制器里集成:

angular.module('myApp', [])
  .controller('StepCtrl', function($scope) {
    // 原始数据
    $scope.rawStepsArray = ["1. Get into car.2. Buckle seat belt.3. Start Ignition"];
    // 拆分处理
    $scope.processedSteps = $scope.rawStepsArray[0]
      .split(/(?=\d+\.)/)
      .filter(step => step.trim() !== '');
  });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:34:59