Insert strings at multiple (but limited) matches in another string

61 views Asked by At

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.

2

There are 2 answers

1
hwnd On BEST ANSWER

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

1
Sergey Yarotskiy On

Just use string.replace method with regex as needle.