-1

I have this string in Javascript:

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

I want it to be the following:

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!!!"

I've tried many things and only this way could my rest of the code work. So a "(xSep)" should come before every four numbers and a "(zSep)" should come after only the first two ": "

Please help me with this. Thank you in advanced.

Nano
  • 21
  • 3

2 Answers2

1

Based off your given output and requirement, you can use the following.

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

Working Demo

hwnd
  • 69,796
  • 4
  • 95
  • 132
  • Thank you very much. It worked really the way I wanted it.. could you please explain the way you did it? – Nano Dec 01 '14 at 16:39
0

Just use string.replace method with regex as needle.

Sergey Yarotskiy
  • 517
  • 4
  • 14
  • I've tried this but I can't get it to replace the four digits with (xSep)theSameFourDigits – Nano Dec 01 '14 at 16:17