【问题标题】:Insert strings at multiple (but limited) matches in another string在另一个字符串中的多个(但有限)匹配处插入字符串
【发布时间】:2014-12-01 16:10:51
【问题描述】:

我在 Javascript 中有这个字符串:

text = "2222 22:22: John: New York /n last year and: the next year /n 3333 33:33: Jack: Los Angeles!!!"

我希望它是以下内容:

newText = "(xSep)2222 22:22:(zSep) John:(zSep) New York /n last year and: the next year /n (xSep)3333 33:33:(zSep) Jack:(zSep) Los Angeles!!!"

我已经尝试了很多东西,只有这样我的其余代码才能工作。 所以一个“(xSep)”应该出现在之前 每四个数字,一个“(zSep)”应该出现在之后 em> 前两个“:”

请帮我解决这个问题。提前谢谢你。

【问题讨论】:

  • 我很困惑 - 你希望 (zsep) 出现在哪里?
  • ": "的前两次出现之后

标签: javascript regex string text-manipulation


【解决方案1】:

根据您给定的输出和要求,您可以使用以下内容。

var res = str.replace(/(\d{4}(?:[^:]*:){2})([^:]*:)/g, '(xSep)$1(zSep)$2(zSep)');

Working Demo

【讨论】:

  • 非常感谢。它真的按照我想要的方式工作..你能解释一下你是怎么做的吗?
【解决方案2】:

只需使用 string.replace 方法和正则表达式作为针。

【讨论】:

  • 我已经尝试过了,但无法用 (xSep)theSameFourDigits 替换四位数字
猜你喜欢
  • 1970-01-01
  • 2012-10-04
  • 2022-01-08
  • 1970-01-01
  • 2015-02-11
  • 2021-08-17
  • 2023-03-08
  • 2011-05-13
  • 1970-01-01
相关资源
最近更新 更多