js 在一个字符串中查找 从某个字符开始到另一个字符的子字符串

1、在这个例子中,findSubstringBetween函数接收一个字符串str,以及要查找的起始字符startChar和终止字符endChar;
2、函数首先找到startChar的位置,并从该位置加上startChar的长度获取开始子字符串的起始索引;
3、然后从这个起始索引开始,使用indexOf查找下一个endChar的位置,得到子字符串的结束索引;
4、最后,使用substring方法提取出从startChar到endChar的子字符串。

javascript 复制代码
const myString = "Hello, @username how are you doing?";
const substringBetween = findSubstringBetween(myString, "@", " ");
console.log(substringBetween); // 输出: username



findSubstringBetween(str, startChar, endChar) {
  const startIndex = str.indexOf(startChar) + startChar.length;
  const endIndex = str.indexOf(endChar, startIndex);
  return str.substring(startIndex, endIndex);
}
相关推荐
KevinWang_14 分钟前
iOS 开发计划(五) - 做一个离线音乐播放器
javascript
狗头大军之江苏分军25 分钟前
前端转行干能干什么?我转行试了下(被迫)
前端·后端
孟陬26 分钟前
Foobar 技术周刊#2:约会已死?用户急剧下滑,约会App大概率会弱化约会属性转向轻陪伴。我有个建议:
前端·后端·rust
parade岁月1 小时前
VTable Guild 3.0.0 发布,面向 Vue 3 的 ProTable 式业务表格
前端
xurileidian2 小时前
第 17 篇 · 边玩边学Python · for 遍历 enumerate 与 zip
java·前端·python
掘金安东尼2 小时前
更多审查智能体,更少盲区:GitHub Copilot 代码审查是怎么做的
前端·github copilot
Hilaku5 小时前
2026 年了,jQuery 真的该死了吗?
前端·javascript·程序员
zach5 小时前
吃透 React setState 同步异步之谜:从批量更新、事件循环到版本演进的完整拆解
前端·react.js
不服老的小黑哥5 小时前
02-从 pnpm dev 到 Spring Boot 启动:后端服务到底怎么跑起来?
前端
htzyl2065 小时前
javaScript——this 的四种绑定:为什么箭头函数改不了它
前端·javascript