Parsing time if valid I need to parse only valid timestamp formats:


Hours followed by minutes followed by seconds: t=1h2m3s
Minutes followed by seconds: t=2m3s
Only hours: t=3h
Only minutes: t=4m
Only seconds: t=5s and escape other timestamp formats like t=2m1h or t=3s2m or t=3s1h2m.


To get the hours, minutes and seconds, I use this Regex. Let me know any improvement can be done to make it simple.

function calculateInSeconds(timeStamp) {
  var timeInSeconds=0;
  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") &gt; -1) {
          timeInSeconds += value * 60 * 60;
       } else if (match.indexOf("m") &gt; -1) {
                timeInSeconds += value * 60;
       } else if (match.indexOf("s") &gt; -1) {
                timeInSeconds += value * 1;
       }
     });
   }
   console.log("timeInSeconds"+timeInSeconds);
}

calculateInSeconds("t=3m59s1h");//invalid
calculateInSeconds("t=1m59s");//valid
calculateInSeconds("t=1h");//valid
First you may improve your regexps a bit using classes: replace [0-9] by \d.

In the other hand, you may strongly improve performance by:


defining an object with the unit values: units: {h: 3600, m: 60, s: 1};
modifying the 2nd regexp to directly provide the current unit:
timeStamp.replace(/(\d+)(\w)/g, function(match, value, unit) {
(note that \w is enough since your previous test eliminated any wrong value)
then using a unique computation in the function: timeInSeconds += value * units[unit];


So the entire snippet becomes:

function calculateInSeconds(timeStamp) {
  var timeInSeconds = 0,
    units = {
    h: 3600,
    m: 60,
    s: 1,
  };
  if (timeStamp.match(/t=\d*h?\d*m?\d*s?/g).toString() == timeStamp){
    timeStamp.replace(/(\d+)(\w)/g, function(match, value, unit) {
      timeInSeconds += value * units[unit];
    });
  }
  console.log(timeStamp + ' -&gt; ' + timeInSeconds + ' seconds');
}

calculateInSeconds("t=3m59s1h"); //invalid
calculateInSeconds("t=1m59s"); //valid
calculateInSeconds("t=1h"); //valid


BTW I like the idea of your first test to isolate valid timeStamps.