bran bran - 3 months ago 27
Javascript Question

Grep ping output to only show latency using javascript

From this:

PING google.com (74.125.68.138) 56(84) bytes of data.
64 bytes from sc-in-f138.1e100.net (74.125.68.138): icmp_seq=1 ttl=48 time=76.8 ms
64 bytes from sc-in-f138.1e100.net (74.125.68.138): icmp_seq=2 ttl=48 time=86.8 ms


I need to separate this part using javascript:

76.8
86.8


So far I came up with this:

'([0-9][0-9][0-9].[0-9] ms|[0-9][0-9].[0-9] ms|[0-9].[0-9] ms)'


But it doesn't seem to work properly when latency reaches more than 2 digits.

Answer

You can use:

/time=(\d+(\.\d+)?) ms$/  // 1: one digit or more
       \_/\______/        // 2: optionally followed by a dot and one digit or more
        1     2           // $: end of input

var ping =
  "64 bytes from sc-in-f138.1e100.net (74.125.68.138): icmp_seq=1 ttl=48 time=76.8 ms";

var time = Number(ping.match(/time=(\d+(\.\d+)?) ms$/)[1]);

console.log(time);