views:

71

answers:

4

I have a string being grabbed from a page in the format "4m 26s", how can I strip this into just seconds?

Many thanks,

+2  A: 

Simple regex will work:

var s = '21m 06s';

var m = /(\d{1,2})m\s(\d{1,2})s/.exec(s);

var mins = parseInt(m[1], 10);
var secs = parseInt(m[2], 10);
Evan Trimboli
-1 regexp is unnecessary
galambalazs
This is a silly comment; you could technically say regexes are always unnecessary. It solves the problem as requested. I could downvote your answer saying that using split is unnecessary.
Evan Trimboli
no, here regexp is slow, harder to read and harder to maintain, thus overcomplicates the problem. you should use regexp when you have a good reason for it. you could've edited your code but you're rather arguing with me.
galambalazs
Slow? Care to back that up with some numbers? I think you'll find there's little to no difference in terms of performance.Harder to read and harder to maintain are subjective, especially since it's a small and easily readable regex. Just because you aren't comfortable with it, doesn't make it complicated.Again, stupid comment.
Evan Trimboli
why is it so hard to admit there is a better way? happens to everyone... *"it's easy to make things bigger, it's hard to make things better..."*
galambalazs
I like how you ignored everything I said. Nice one ;)
Evan Trimboli
A: 
var str = "4m 26s";
console.log(str.match(/\d+m\s+(\d+)s/)[1]);//26
Amarghosh
+2  A: 

A non-regex way:

Do a string.split(" ") on your string; then do string.slice(0, -1) on both arrays. Multiply the first entry by 60. Add them together.

Jan Kuboschek
+2  A: 
var str = "4m 26s";
var arr = str.split(" ");
var sec = parseInt(arr[0], 10)*60 + parseInt(arr[1], 10);

You don't need regex if you use parseInt...

galambalazs