javascript - Parsing t=1h2m3s(h - hour, m-minutes, s-seconds ) into seconds if order of hours, minutes and seconds are valid -


i need parse valid timestamp formats below

  1. hours followed minutes followed seconds ex:t=1h2m3s
  2. minutes followed seconds ex:t=2m3s
  3. only hours ex: t =3h
  4. only minutes ex: t =4m
  5. only seconds ex: t =5s

and escape other timestamp formats t=2m1h or t=3s2m or t=3s1h2m.

i tried below unable escape invalid formats.i trying regular expression find.

 function calculateinseconds(timestamp) {         var timeinseconds=0;         console.log("calculateinseconds timestamp:"+timestamp);          timestamp.replace(/([0-9]+)[h|m|s]/g, function(match, value) {             if (match.indexof("h") > -1) {                 timeinseconds += value * 60 * 60;             } else if (match.indexof("m") > -1) {                 timeinseconds += value * 60;             } else if (match.indexof("s") > -1) {                 timeinseconds += value * 1;             }          });         console.log("timeinseconds"+timeinseconds);      } calculateinseconds("t=20m2s"); 

i first check order matches then, if calculate time in seconds.

function calculateinseconds(timestamp) {    var timeinseconds=0;    console.log("calculateinseconds timestamp:"+timestamp);    if(timestamp.match(/t=[0-9]*h?[0-9]*m?[0-9]*s?/g).tostring()==timestamp){      timestamp.replace(/([0-9]+)[h|m|s]/g, function(match, value) {         if (match.indexof("h") > -1) {            timeinseconds += value * 60 * 60;         } else if (match.indexof("m") > -1) {                  timeinseconds += value * 60;         } else if (match.indexof("s") > -1) {                  timeinseconds += value * 1;         }       });     }     console.log("timeinseconds"+timeinseconds);  }  calculateinseconds("t=1h2m");//3720 valid  calculateinseconds("t=2m1h");//0 invalid


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -