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

如何获取指定字符串与另一字符串首次出现之间的子串?

解决方法
  • indexOf()本身就是返回指定字符串首次出现的索引,不存在firstIndexOf()方法,直接用indexOf()即可。
  • 要提取my name is,只需找到第一个Barbara的起始位置,从Hello之后截取到该位置之前即可。

代码示例

const myString = 'Hello my name is Barbara but i dont really like the name Barbara I prefer Barb'

// 获取第一个"Barbara"的起始索引
const firstBarbaraIndex = myString.indexOf("Barbara");
// 从"Hello"后截取到第一个Barbara之前,再去除末尾空格
const mySubString = myString.substring(myString.indexOf("Hello") + 6, firstBarbaraIndex).trimEnd();
console.log(mySubString); // 输出: my name is

补充写法

如果不想用trimEnd(),可以直接调整截取的结束位置(减去1以跳过Barbara前的空格):

const mySubString = myString.substring(myString.indexOf("Hello") + 6, firstBarbaraIndex - 1);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:45:05