Roman Iuvshin
Roman Iuvshin

Reputation: 1912

Parsing log with JavaScript

I need extract only "40:37.298s" from:

Total time: 40:37.298s

using JS, but I`m new in JS, can some one help?

Upvotes: 1

Views: 1996

Answers (7)

user160820
user160820

Reputation: 15220

I would say use a RegEx like [:\.0-9]*s

for example

yourText.match("regex")

in your case it will be

"Total time: 40:37.298s".match("[:\.0-9]*s")[0]

It will return 40:37.298s

Upvotes: 0

Wayne
Wayne

Reputation: 60424

There are many ways to do this. Here's one:

var str = "Total time: 40:37.298s";
str.split(": ")[1]

In most cases I prefer splitting on some known pivot, rather than trying to extract a specific substring (as others have shown) for the following reasons:

  • It's more flexible; this will still work if the first part of the string contains slight variations (but the substring method won't)
  • It's easier to see what's being extracted (but the substring method requires that I manually count positions in the string to verify that I'm selecting the right thing)

Upvotes: 2

Alex
Alex

Reputation: 35407

var time = 'Total time: 40:37.298s';

time = time.match(/\d{1,2}:\d{1,2}\.\d+s/);

http://jsfiddle.net/ypzgJ/

Upvotes: 1

Alberto De Caro
Alberto De Caro

Reputation: 5213

var item = 'Total time: 40:37.298s';
var pattern = /\d{1,2}\:\d{2}\.\d{3}s/g;
var res = pattern.exec(item);

That is:

  • \d{1,2} one or two digits
  • \: the ':' char
  • \d{2} two digits
  • . the '.' char
  • \d{3} three digits
  • s the 's' char

Upvotes: 0

Nicocube
Nicocube

Reputation: 2992

var result = "Total time: 40:37.298s".replace(/^.*([0-9]{2}:[0-9]{2}\.[0-9]{3}s)/g,'$1')

Upvotes: 0

Me1000
Me1000

Reputation: 1758

the substring method is what you're looking for:

"Total time: 40:37.298s".substring("Total time: ".length);

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318598

> 'Total time: 40:37.298s'.substr(12)
'40:37.298s'

If you want to use a regex for more flexibility:

> /([0-9]+:[0-9]+\.[0-9]+s)/.exec('Total time: 40:37.298s')[1]
'40:37.298s'

Upvotes: 6

Related Questions