【问题标题】:Javascript split string by another string and include that another string that was used to split it into result [duplicate]Javascript将字符串拆分为另一个字符串,并包含另一个用于将其拆分为结果的字符串[重复]
【发布时间】:2017-12-19 22:00:03
【问题描述】:

如果我有这个字符串:“MyStringToForSplitting”,我想用这个词“ring”来分割它。 如果我这样做:"MyStringToForSplitting".split('ring') 我将得到包含这些元素的数组:

  1. 我的朋友
  2. ToForSplitting

我想不出最好的方法来拆分它并在结果数组中包含“ring”,如下所示:

1.MyS

2.环

3.拆分

【问题讨论】:

  • 抱歉重复。没找到那个...

标签: javascript string split


【解决方案1】:

您可以使用 regex 并捕获拆分模式:

console.log("MyStringToForSplitting".split(/(ring)/));

var s = "ring";
var p = new RegExp("(" + s + ")")
console.log("MyStringForSplitting".split(p))

【讨论】:

  • 什么是环是变量而不是硬编码字符串?
  • 您可以从字符串变量构造正则表达式,然后将其用于拆分。查看更新。
  • 如果你想忽略大小写,那么可以使用 new RegExp("(" + s + ")","i")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多