1

I need to replace everything between : and , with a | multiple times.
I have a server list like server1:127.0.0.1,server2:127.0.0.2,server3:127.0.0.3.

Basically, I need to remove all the IPs and replace them with some |.

So far I was able to do this:

resultList = serverList.replace(/:.*,/g, '|')

The problem is that the result list is server1|server3:127.0.0.3.

How can I replace every occurrence?

Ivan
  • 34,531
  • 8
  • 55
  • 100
radicaled
  • 2,369
  • 5
  • 30
  • 44
  • greedy matching ruins your regex. Use `[^,]*` instead of `.*` – ASDFGerte Jun 11 '18 at 21:38
  • Possible duplicate of [how to replace all occurrence of string between two symbols?](https://stackoverflow.com/questions/25606731/how-to-replace-all-occurrence-of-string-between-two-symbols) – Heretic Monkey Jun 11 '18 at 21:52

2 Answers2

5

/:.*,/ is greedily matching :127.0.0.1,server2:127.0.0.2. Remember that quantifiers like * will match as much as they can while still allowing the rest of the pattern to match.

Consider specifying [^,] instead of .. This will exclude commas from matching and therefore limit the match to just the region you want to remove.

resultList = serverList.replace(/:[^,]*,/g, '|')
Mamun
  • 66,969
  • 9
  • 47
  • 59
cdhowie
  • 158,093
  • 24
  • 286
  • 300
2

You could take a lazy approach with ? (Matches as few characters as possible).

var string = 'server1:127.0.0.1,server2:127.0.0.2,server3:127.0.0.3';

console.log(string.replace(/:.*?(,|$)/g, '|'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392