Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript Regex replacing multiple patterns

I need to modify the regex, which does the following for me.

Changes the IP list, the list can be longer or shorter.

1.1.1.1,2.2.2.2

to a string such as:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{"{#ADDR}":"1.1.1.1"},{"{#ADDR}":" 2.2.2.2"}]

in the following line:

return '{$PING_LIST}'.replace(/([^,]+)/g,'{"{#ADDR}":"$1"}').replace(/(.*)/,'[$1]')

But I need to add the hostname to the list as well.

1.1.1.1-NODE1,2.2.2.2-NODE2

and get something like this

[{"{#ADDR}":"1.1.1.1","{#NODE}":"NODE1"},{"{#ADDR}":"2.2.2.2","{#NODE}":"NODE2"}]

I tried to get the hostname, this way:

(?<=-)(\w+)(?=,)

but I can’t figure out the correct syntax and combine it with the previous expression.

Very grateful for any help!

>Solution :

Use ((?:\d+\.){3}\d+) to match the IP.

let pinglist = '1.1.1.1-NODE1,2.2.2.2-NODE2';
let result = pinglist.replace(/((?:\d+\.){3}\d+)-([^,]+)/g, '{"{#ADDR}":"$1","{#NODE}":"$2"}')
console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading