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?

2

2 Answers 2

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, '|')
Sign up to request clarification or add additional context in comments.

Comments

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, '|'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.