2014-12-01 77 views
-1

我有这个字符串在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)”应前两个来了“:”

请帮助我。先进的谢谢你。

+0

我很困惑 - 正是你想要的(zsep)出现? – ekrah 2014-12-01 16:17:53

+0

只有前两次出现':“' – Nano 2014-12-01 16:21:35

回答

1

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

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

Working Demo

+0

非常感谢。它的工作方式真的是我想要的方式..你能解释一下你做到的方式吗? – Nano 2014-12-01 16:39:43

0

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

+0

我试过这个,但我不能用它替换四个数字(xSep)theSameFourDigits – Nano 2014-12-01 16:17:39