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:
JavaScript
x
13
13
1
fl=47f54
2
h=www.cloudflare.com
3
ip=11.111.11.11
4
ts=1597428248.652
5
visit_scheme=https
6
uag=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
7
colo=OH
8
http=http/2
9
loc=US
10
tls=TLSv1.3
11
sni=plaintext
12
warp=off
13
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.
JavaScript
1
6
1
2
ip=11.111.11.11
3
4
uag=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
5
6
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:
JavaScript
1
2
1
^(?:ip|uag)=(.*)$
2
Explanation of the above regex:
^, $
– Represents start and end of the line respectively.(?:ip|uag)
– Represents a non-capturing group matching eitherip
oruag
literally.=
– Represents=
literally.(.*)
– Represents first caturing group matching anything zero or more time which is preceded byip=
oruag=
.
You can find the demo of the above regex in here.
JavaScript
1
22
22
1
const myRegexp = /^(?:ip|uag)=(.*)$/gm;
2
const myString = `fl=47f54
3
h=www.cloudflare.com
4
ip=11.111.11.11
5
ts=1597428248.652
6
visit_scheme=https
7
uag=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
8
colo=OH
9
http=http/2
10
loc=US
11
tls=TLSv1.3
12
sni=plaintext
13
warp=off`;
14
let match;
15
16
let resultString = "";
17
match = myRegexp.exec(myString);
18
while (match != null) {
19
resultString = resultString.concat(match[1] + "n");
20
match = myRegexp.exec(myString);
21
}
22
console.log(resultString);
2nd approach:
JavaScript
1
14
14
1
const myString = `fl=47f54
2
h=www.cloudflare.com
3
ip=11.111.11.11
4
ts=1597428248.652
5
visit_scheme=https
6
uag=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
7
colo=OH
8
http=http/2
9
loc=US
10
tls=TLSv1.3
11
sni=plaintext
12
warp=off`;
13
// Split on new line filter on the condition that element starts with ip or uag and join
14
console.log(myString.split("n").filter(el => el.startsWith("ip") || el.startsWith("uag")).join('n'));