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

JavaScript中如何无视前缀长度从指定单词处开始截取字符串?

实现方法

你可以组合使用indexOf()和slice()两个原生字符串方法实现需求,无需提前预知"fox"的位置:

  • 先用indexOf('fox')获取目标子串第一次出现的起始索引
  • 再用slice()从该索引位置开始截取到字符串末尾

示例代码

var string1 = "The quick brown fox jumps over the lazy dog.";
var string2 = "The sluggish, purple fox jumps over a rapid cat.";

function getFromFox(str) {
  const foxStart = str.indexOf('fox');
  // 兼容字符串中不存在fox的异常场景
  return foxStart < 0 ? '' : str.slice(foxStart);
}

// 测试输出
console.log(getFromFox(string1)); // 输出:fox jumps over the lazy dog.
console.log(getFromFox(string2)); // 输出:fox jumps over a rapid cat.

如果需要匹配字符串中所有出现的"fox"及对应后续内容,可使用正则方案:

function getAllFromFox(str) {
  const reg = /fox.*?(?=fox|$)/g;
  return str.match(reg) || [];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:06:03