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

如何在TypeScript中将含‘,,,’的字符串拆分为两个变量?

解决字符串分割问题:提取指定部分并去除分隔符

嘿,我明白你想要实现的需求了——把这个包含,,,分隔符的字符串拆成两个独立变量,对吧?其实不用纠结substr(),有个更简洁灵活的方法:split()函数,专门用来按指定分隔符分割字符串,完美适配你的场景。

具体实现步骤:

  • 用,,,作为分隔符,把原字符串分割成一个数组
  • 数组的第一个元素就是你要的strOne,第二个元素就是strTwo

代码示例:

const str = 'SVchnsSoQQjr5kafygOh,,,Skyrim';
const [strOne, strTwo] = str.split(',,,');

console.log(strOne); // 输出: 'SVchnsSoQQjr5kafygOh'
console.log(strTwo); // 输出: 'Skyrim'

补充:如果你坚持想用substr()的话

也可以通过先找到分隔符的起始索引来实现,不过相对麻烦一点:

const str = 'SVchnsSoQQjr5kafygOh,,,Skyrim';
const separatorIndex = str.indexOf(',,,');
const strOne = str.substr(0, separatorIndex);
const strTwo = str.substr(separatorIndex + 3); // 3是分隔符`,,,`的长度

console.log(strOne); // 同样得到目标结果
console.log(strTwo);

两种方法都能达成你的目标,但split()显然更直观也更易维护,尤其是如果以后分隔符长度有变化的话,不用手动调整数字~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:42:20