2014-12-01 72 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