Your Regex accepts the formats t=1h2s
and t=1h2m
. I'm not sure if this is intentional or not.
Your Regex also accepts t=1hms
, t=h1ms
, and t=hm1s
. Technically, t=hms
passes your matching Regex as well, though it will output 0 like an invalid match. These cases can be eliminated by changing your 0-or-more *
symbols to 1-or-more +
symbols. Since this is Code Review, I'll retain your original functionality in my answer.
Finally, you're using pipes within your character set [h|m|s]
when you shouldn't be: as characters within a character set are treated as literals, this includes |
as a valid matching character (i.e., \d*[h|m|s]
would successfully match 65|
). It should just be [hms]
.
timeStamp.match(...)==timeStamp
seems to be used to make sure the expression matches the whole string, but there are better ways to accomplish this. In Regex, you can specify ^
and $
as the start and end of the string respectively.
You can combine the match and replace into a single expression, since the replace won't do anything if it fails to match. Then you can use Regex groups to capture the hours, minutes, and seconds.
Finally, you can replace [0-9]
in your regular expression to the digit (\d
) character set, which represents the same thing. This is only really useful if you're interested in shortening the pattern; I don't think it improves readability.
Putting everything together, we get the following Regex pattern:
/^t=(?:(\d*)h)?(?:(\d*)m)?(?:(\d*)s)?$/
Breaking it down:
/^t= ## The start of the string
(?: ## Non-capturing group
(\d*)h ## Capturing hours in a group
)? ## Specifying the group as optional
(?:(\d*)m)? ## Same for minutes
(?:(\d*)s)? ## Same for seconds
$/ ## The end of the string
Resulting in the following JavaScript code:
function calculateInSeconds(timeStamp) {
var timeInSeconds = 0;
timeStamp.replace(/^t=(?:(\d*)h)?(?:(\d*)m)?(?:(\d*)s)?$/, function(match, hours, minutes, seconds) {
var hoursInSeconds, minutesInSeconds;
hoursInSeconds = hours * 60 * 60 || 0;
minutesInSeconds = minutes * 60 || 0;
seconds = seconds * 1 || 0;
timeInSeconds = hoursInSeconds + minutesInSeconds + seconds;
});
console.log("timeInSeconds"+timeInSeconds);
}