Javascript split () in time bar

I have a line that can be in the following formats (numbers are examples):

2h34m2s 23m6s 7h8s 4h2m 3h 2m 2s 

I was originally going to use split() with a regex to match h , m and s . However, this would not work if only some indicators were present (if it is a 2m3s form, then I need a way to find out that the first record in the array represents minutes, not hours).

I assume that the correct solution will be associated with some regex expression, but it eludes me. Any ideas for a clean and efficient solution?

edit:

(I would like to accept any number of digits, so I do not use {1,2} in the regular expression.

 var timeString = $('#interval').val(); var hours = timeString.match('/\d+(?=h)/')[0]; // 2h4m8s var minutes = timeString.match('/\d+(?=m)/')[0]; var seconds = timeString.match('/\d+(?=s)/')[0]; console.log('hours: ' + hours); console.log('minutes: ' + minutes); console.log('seconds: ' + seconds); 

The console gives null for values.

+4
source share
4 answers

You can use regex with positive images:

 /\d{1,2}(?=h)/ 

Will correspond to the clock: one or two digits, followed by the letter h . Similarly for m and s .

+1
source

You can use the following regular expressions:

\d+(?=m) for minutes,

\d+(?=h) for several hours and

\d+(?=s) in seconds.

You should probably make case insensitive.

+2
source
 var string = "23h4m" var regexp = /(\d+h)?(\d+m)?(\d+s)?/; var result = string.match(regexp) // gives you ["23h4m", "23h", "4m", undefined] 

You can get the result with result[1] for hours, result[2] for minutes and result[3] for several seconds. Values ​​are undefined if not specified.

+2
source
 //match any digits and include the letters var rx=/((\d+)(h|m|s))/g; //test: var str1='2h34m2s',str2='23m6s'; str1+'=\n\t'+str1.match(rx).join(':\n\t')+'\n'+ str2+'=\n\t'+str2.match(rx).join(':\n\t') //returns 2h34m2s= 2h: 34m: 2s 23m6s= 23m: 6s 
+1
source

All Articles