Skip to content
Advertisement

Extract ip and uag from Cloudflare cdn-cgi/trace text result using regex in JS

Hi I am planning to use Cloudflare cdn-cgi trace service to get clients IP and User Agent results. If I fetch this link: https://www.cloudflare.com/cdn-cgi/trace, the result I am getting is in a text format. Result text example:

fl=47f54
h=www.cloudflare.com
ip=11.111.11.11
ts=1597428248.652
visit_scheme=https
uag=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
colo=OH
http=http/2
loc=US
tls=TLSv1.3
sni=plaintext
warp=off

I did some research and figured out I need to use Regex? But not sure how to extract only the ip and uag from the result.

...
ip=11.111.11.11
...
uag=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
...

How do I just extract the result 11.111.11.11 (ip changes for all client) and Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 (uag or user agent changes for all client) from the above text for each result I fetch?

Advertisement

Answer

You may try:

^(?:ip|uag)=(.*)$

Explanation of the above regex:

  • ^, $ – Represents start and end of the line respectively.
  • (?:ip|uag) – Represents a non-capturing group matching either ip or uag literally.
  • = – Represents = literally.
  • (.*) – Represents first caturing group matching anything zero or more time which is preceded by ip= or uag=.

You can find the demo of the above regex in here.

const myRegexp = /^(?:ip|uag)=(.*)$/gm;
const myString = `fl=47f54
h=www.cloudflare.com
ip=11.111.11.11
ts=1597428248.652
visit_scheme=https
uag=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
colo=OH
http=http/2
loc=US
tls=TLSv1.3
sni=plaintext
warp=off`;
let match;

let resultString = "";
match = myRegexp.exec(myString);
while (match != null) {
  resultString = resultString.concat(match[1] + "n");
  match = myRegexp.exec(myString);
}
console.log(resultString);

2nd approach:

const myString = `fl=47f54
h=www.cloudflare.com
ip=11.111.11.11
ts=1597428248.652
visit_scheme=https
uag=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
colo=OH
http=http/2
loc=US
tls=TLSv1.3
sni=plaintext
warp=off`;
// Split on new line filter on the condition that element starts with ip or uag and join
console.log(myString.split("n").filter(el => el.startsWith("ip") || el.startsWith("uag")).join('n'));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement