peke_peke peke_peke - 5 months ago 6
Node.js Question

parsing some values from string in nodeJS

What's the best way in nodeJS to parse to following string to extract values described below?

client 111.222.333.44#59699: query: jadssdffsdnisa.website.com IN A -ED (81.11.11.175)


Current code:

//parsing
var c_ip = data.split("client ")[1].split("#")[0]
var sdomain = data.split("query:")[1].split(".")[0]

console.log("c_ip: " + c_ip + '\n');
console.log("sdomain: " + sdomain + '\n');


Results in:

c_ip: 130.225.244.66

sdomain: paul

Answer

This very depends on how your input string arrives but assuming that it has always that same format you could do something like this

var task = "client 111.222.333.44#59699: query: jadssdffsdnisa.website.com IN A -ED (81.11.11.175)"

var c_ip = task.split("client ")[1].split("#")[0]
var sdomain  = task.split("query: ")[1].split(".")[0] 

console.log("c_ip:", c_ip)
console.log("sdomain:", sdomain)

further, if it varies more you could use regex. @jens-habegger has a good example