Convert a string like 4h53m12s to a total number of seconds in JavaScriptDetermine total number of seconds since the epochMilliseconds to Time string & Time string to MillisecondsConvert number into hours : minutesConvert string to spinal caseJavaScript get total functionConvert hours and minutes to total minutesConvert seconds to hours/minutes/seconds and pretty printConvert a string in time format to minutesConvert HTML input string to JavaScript Array literalConvert query string into object in JavaScript

Monty Hall Problem with a Fallible Monty

How were the LM astronauts supported during the moon landing and ascent? What were the max G's on them during these phases?

Inadvertently nuked my disk permission structure - why?

How important is a good quality camera for good photography?

Would it be a good idea to memorize relative interval positions on guitar?

Current relevance: "She has broken her leg" vs. "She broke her leg yesterday"

Marketing Cloud Query Activity is not pulling in data for newly added fields to target Data Extension

Company messed up with patent and now a lawyer is coming after me

How can I make sure my players' decisions have consequences?

Memory capability and powers of 2

Are glider winch launches rarer in the USA than in the rest of the world? Why?

Spoken encryption

"I you already know": is this proper English?

Strange Cron Job takes up 100% of CPU Ubuntu 18 LTS Server

Is it normal practice to screen share with a client?

Closet Wall, is it Load Bearing?

What was the rationale behind 36 bit computer architectures?

Grid/table with lots of buttons

Which creatures count as green creatures?

Can GPL and BSD licensed applications be used for government work?

What does the minus sign mean in measurements in datasheet footprint drawings?

Convert a string like 4h53m12s to a total number of seconds in JavaScript

Why are off grid solar setups only 12, 24, 48 VDC?

Hold[Expression] (or similar) in InputField that truly holds the input unmodified



Convert a string like 4h53m12s to a total number of seconds in JavaScript


Determine total number of seconds since the epochMilliseconds to Time string & Time string to MillisecondsConvert number into hours : minutesConvert string to spinal caseJavaScript get total functionConvert hours and minutes to total minutesConvert seconds to hours/minutes/seconds and pretty printConvert a string in time format to minutesConvert HTML input string to JavaScript Array literalConvert query string into object in JavaScript






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3












$begingroup$


At the moment I have this:






function getValue(str)

let result = 0;

var regex = /(d+[a-z]+)/g;
match = regex.exec(str);

while (match != null)

var match_str = match[0];
var last_char = match_str[match_str.length-1];

if ( last_char == 'h' )
result += parseInt(match_str) * 3600;
if ( last_char == 'm' )
result += parseInt(match_str) * 60;
if ( last_char == 's' )
result += parseInt(match_str);

match = regex.exec(str);


return result;


console.log( getValue("4h12m32s") );





It feels quite clumsy though. Also checking invalid values like 4hs feels difficult.



Is there any clever trick for something similar?










share|improve this question











$endgroup$











  • $begingroup$
    +"4h12m32s".replace(/(d+)h(d+)m(d+)s/, (_, h, m, s) => (h * 3600) + (m * 60) + (s * 1)) ;)
    $endgroup$
    – user11536834
    7 hours ago










  • $begingroup$
    (might as well enjoy that implicit type coercion)
    $endgroup$
    – user11536834
    7 hours ago










  • $begingroup$
    @user11536834 I would expect that each unit is optional. The current code allows that; your solution doesn't.
    $endgroup$
    – 200_success
    7 hours ago

















3












$begingroup$


At the moment I have this:






function getValue(str)

let result = 0;

var regex = /(d+[a-z]+)/g;
match = regex.exec(str);

while (match != null)

var match_str = match[0];
var last_char = match_str[match_str.length-1];

if ( last_char == 'h' )
result += parseInt(match_str) * 3600;
if ( last_char == 'm' )
result += parseInt(match_str) * 60;
if ( last_char == 's' )
result += parseInt(match_str);

match = regex.exec(str);


return result;


console.log( getValue("4h12m32s") );





It feels quite clumsy though. Also checking invalid values like 4hs feels difficult.



Is there any clever trick for something similar?










share|improve this question











$endgroup$











  • $begingroup$
    +"4h12m32s".replace(/(d+)h(d+)m(d+)s/, (_, h, m, s) => (h * 3600) + (m * 60) + (s * 1)) ;)
    $endgroup$
    – user11536834
    7 hours ago










  • $begingroup$
    (might as well enjoy that implicit type coercion)
    $endgroup$
    – user11536834
    7 hours ago










  • $begingroup$
    @user11536834 I would expect that each unit is optional. The current code allows that; your solution doesn't.
    $endgroup$
    – 200_success
    7 hours ago













3












3








3





$begingroup$


At the moment I have this:






function getValue(str)

let result = 0;

var regex = /(d+[a-z]+)/g;
match = regex.exec(str);

while (match != null)

var match_str = match[0];
var last_char = match_str[match_str.length-1];

if ( last_char == 'h' )
result += parseInt(match_str) * 3600;
if ( last_char == 'm' )
result += parseInt(match_str) * 60;
if ( last_char == 's' )
result += parseInt(match_str);

match = regex.exec(str);


return result;


console.log( getValue("4h12m32s") );





It feels quite clumsy though. Also checking invalid values like 4hs feels difficult.



Is there any clever trick for something similar?










share|improve this question











$endgroup$




At the moment I have this:






function getValue(str)

let result = 0;

var regex = /(d+[a-z]+)/g;
match = regex.exec(str);

while (match != null)

var match_str = match[0];
var last_char = match_str[match_str.length-1];

if ( last_char == 'h' )
result += parseInt(match_str) * 3600;
if ( last_char == 'm' )
result += parseInt(match_str) * 60;
if ( last_char == 's' )
result += parseInt(match_str);

match = regex.exec(str);


return result;


console.log( getValue("4h12m32s") );





It feels quite clumsy though. Also checking invalid values like 4hs feels difficult.



Is there any clever trick for something similar?






function getValue(str)

let result = 0;

var regex = /(d+[a-z]+)/g;
match = regex.exec(str);

while (match != null)

var match_str = match[0];
var last_char = match_str[match_str.length-1];

if ( last_char == 'h' )
result += parseInt(match_str) * 3600;
if ( last_char == 'm' )
result += parseInt(match_str) * 60;
if ( last_char == 's' )
result += parseInt(match_str);

match = regex.exec(str);


return result;


console.log( getValue("4h12m32s") );





function getValue(str)

let result = 0;

var regex = /(d+[a-z]+)/g;
match = regex.exec(str);

while (match != null)

var match_str = match[0];
var last_char = match_str[match_str.length-1];

if ( last_char == 'h' )
result += parseInt(match_str) * 3600;
if ( last_char == 'm' )
result += parseInt(match_str) * 60;
if ( last_char == 's' )
result += parseInt(match_str);

match = regex.exec(str);


return result;


console.log( getValue("4h12m32s") );






javascript parsing datetime regex unit-conversion






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 7 hours ago









200_success

135k21 gold badges172 silver badges442 bronze badges




135k21 gold badges172 silver badges442 bronze badges










asked 8 hours ago









Dirk BoerDirk Boer

3962 silver badges10 bronze badges




3962 silver badges10 bronze badges











  • $begingroup$
    +"4h12m32s".replace(/(d+)h(d+)m(d+)s/, (_, h, m, s) => (h * 3600) + (m * 60) + (s * 1)) ;)
    $endgroup$
    – user11536834
    7 hours ago










  • $begingroup$
    (might as well enjoy that implicit type coercion)
    $endgroup$
    – user11536834
    7 hours ago










  • $begingroup$
    @user11536834 I would expect that each unit is optional. The current code allows that; your solution doesn't.
    $endgroup$
    – 200_success
    7 hours ago
















  • $begingroup$
    +"4h12m32s".replace(/(d+)h(d+)m(d+)s/, (_, h, m, s) => (h * 3600) + (m * 60) + (s * 1)) ;)
    $endgroup$
    – user11536834
    7 hours ago










  • $begingroup$
    (might as well enjoy that implicit type coercion)
    $endgroup$
    – user11536834
    7 hours ago










  • $begingroup$
    @user11536834 I would expect that each unit is optional. The current code allows that; your solution doesn't.
    $endgroup$
    – 200_success
    7 hours ago















$begingroup$
+"4h12m32s".replace(/(d+)h(d+)m(d+)s/, (_, h, m, s) => (h * 3600) + (m * 60) + (s * 1)) ;)
$endgroup$
– user11536834
7 hours ago




$begingroup$
+"4h12m32s".replace(/(d+)h(d+)m(d+)s/, (_, h, m, s) => (h * 3600) + (m * 60) + (s * 1)) ;)
$endgroup$
– user11536834
7 hours ago












$begingroup$
(might as well enjoy that implicit type coercion)
$endgroup$
– user11536834
7 hours ago




$begingroup$
(might as well enjoy that implicit type coercion)
$endgroup$
– user11536834
7 hours ago












$begingroup$
@user11536834 I would expect that each unit is optional. The current code allows that; your solution doesn't.
$endgroup$
– 200_success
7 hours ago




$begingroup$
@user11536834 I would expect that each unit is optional. The current code allows that; your solution doesn't.
$endgroup$
– 200_success
7 hours ago










2 Answers
2






active

oldest

votes


















4












$begingroup$


  • getValue(str) is such a vague name for the function and its parameter, it could mean anything! Furthermore, "get" implies that this is a getter function that retrieves something, which is not the case.

  • Your regex is ineffective. Capturing parentheses could be useful, but you didn't actually use them right, such that you ended up having to pass a dirty string to parseInt() and extract the last character the harder way.

  • You neglected to scope match, such that it acts as a global variable. The regex-matching statement is written twice; the assignment could be done within the loop condition instead.

  • The if statements should be an if-else chain, since the conditions are mutually exclusive. However, since the branches are all so similar, a lookup table would be more elegant.




function durationSeconds(timeExpr)

var units = 'h': 3600, 'm': 60, 's': 1;
var regex = /(d+)([hms])/g;

let seconds = 0;
var match;
while ((match = regex.exec(timeExpr)))

seconds += parseInt(match[1]) * units[match[2]];


return seconds;


console.log( durationSeconds("4h12m32s") );





Alternatively, if you expect that the units will be in the conventional order, you don't have to loop at all.






function durationSeconds(timeExpr)
0)
+ 60 * (parseInt(match[2])

console.log( durationSeconds("4h32s") );








share|improve this answer











$endgroup$




















    2












    $begingroup$

    Named Capture Groups



    JavaScript RegExp has named capture groups that can make life a lot simpler when dealing with complicated RegExp. Combined with destructuring assignment you can extract the named hours minutes and seconds as follows.



    function toSeconds(time) 
    const groups: h = 0, m = 0, s = 0 = /(?<h>d*)h(?<m>d*)m(?<s>d*)/i.exec(time);
    return h * 3.6e3 + m * 60 + s * 1; // * 1 to coerce s to Number



    Missing digits are set to zero in the assignment defaults.



    However this is limited to strings that have hours, minutes, and seconds in the correct order (hence no need to match the "s") and will throw an error if there is a problem.



    A more robust solution



    You can also reduce the array created by symbol.matchAll (it returns an iterator that you convert to an array via spread operator)



    It RegExp[symbol.matchAll] is the same call as String.matchAll(RegExp)



    To handle as many variations as possible you can convert the time string to lowercase, soak up white spaces, allow for fractions, multiple periods, and negative periods.



    Using an IIF to wrap the periods constant via closure the function looks like



    const toSeconds = (() => 
    const periods = h: 3600, m: 60, s: 1;
    return time => [.../(-*d*.*d*)W*([hms])/g[Symbol.matchAll](time.toLowerCase())]
    .reduce((time, [, digits, type]) => periods[type] * digits + time, 0);
    )();


    Or via the string



    const toSeconds = (() => 
    const periods = h: 3600, m: 60, s: 1;
    return time => [...time.toLowerCase().matchAll(/(-*d*.*d*)W*([hms])/g)]
    .reduce((time, [, digits, type]) => periods[type] * digits + time, 0);
    )();


    The snippet below shows some of the results of a variety of inputs.






    const toSeconds = (() => 
    const periods = h: 3600, m: 60, s: 1;
    return time => [.../(-*d*.*d*)W*([hms])/g[Symbol.matchAll](time.toLowerCase())]
    .reduce((time, [, digits, type]) =>periods[type] * digits + time, 0);
    )();



    "1h,1m,1s,1,,1s2m3h,3h2m1s,2H2M2S,1h 1H1s1 S1m1M,1.1s,1.2s,s,1h-5m,1 1s,hms"
    .split(",")
    .forEach(time => log(""" + time + "" =" , toSeconds(time)+" seconds"));

    function log(...data)
    document.body.appendChild(
    Object.assign(
    document.createElement("div"), textContent: data.join(" ")
    )
    )





    BTW in Javascript we put...



    • the opening { on the same line as the statement,

    • use camelCase for naming.

    And from many years of C style language experience I would advise you to always delimit statement blocks with eg Bad if (foo) bar = foo, Good if (foo) bar = foo






    share|improve this answer









    $endgroup$















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "196"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f224931%2fconvert-a-string-like-4h53m12s-to-a-total-number-of-seconds-in-javascript%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4












      $begingroup$


      • getValue(str) is such a vague name for the function and its parameter, it could mean anything! Furthermore, "get" implies that this is a getter function that retrieves something, which is not the case.

      • Your regex is ineffective. Capturing parentheses could be useful, but you didn't actually use them right, such that you ended up having to pass a dirty string to parseInt() and extract the last character the harder way.

      • You neglected to scope match, such that it acts as a global variable. The regex-matching statement is written twice; the assignment could be done within the loop condition instead.

      • The if statements should be an if-else chain, since the conditions are mutually exclusive. However, since the branches are all so similar, a lookup table would be more elegant.




      function durationSeconds(timeExpr)

      var units = 'h': 3600, 'm': 60, 's': 1;
      var regex = /(d+)([hms])/g;

      let seconds = 0;
      var match;
      while ((match = regex.exec(timeExpr)))

      seconds += parseInt(match[1]) * units[match[2]];


      return seconds;


      console.log( durationSeconds("4h12m32s") );





      Alternatively, if you expect that the units will be in the conventional order, you don't have to loop at all.






      function durationSeconds(timeExpr)
      0)
      + 60 * (parseInt(match[2])

      console.log( durationSeconds("4h32s") );








      share|improve this answer











      $endgroup$

















        4












        $begingroup$


        • getValue(str) is such a vague name for the function and its parameter, it could mean anything! Furthermore, "get" implies that this is a getter function that retrieves something, which is not the case.

        • Your regex is ineffective. Capturing parentheses could be useful, but you didn't actually use them right, such that you ended up having to pass a dirty string to parseInt() and extract the last character the harder way.

        • You neglected to scope match, such that it acts as a global variable. The regex-matching statement is written twice; the assignment could be done within the loop condition instead.

        • The if statements should be an if-else chain, since the conditions are mutually exclusive. However, since the branches are all so similar, a lookup table would be more elegant.




        function durationSeconds(timeExpr)

        var units = 'h': 3600, 'm': 60, 's': 1;
        var regex = /(d+)([hms])/g;

        let seconds = 0;
        var match;
        while ((match = regex.exec(timeExpr)))

        seconds += parseInt(match[1]) * units[match[2]];


        return seconds;


        console.log( durationSeconds("4h12m32s") );





        Alternatively, if you expect that the units will be in the conventional order, you don't have to loop at all.






        function durationSeconds(timeExpr)
        0)
        + 60 * (parseInt(match[2])

        console.log( durationSeconds("4h32s") );








        share|improve this answer











        $endgroup$















          4












          4








          4





          $begingroup$


          • getValue(str) is such a vague name for the function and its parameter, it could mean anything! Furthermore, "get" implies that this is a getter function that retrieves something, which is not the case.

          • Your regex is ineffective. Capturing parentheses could be useful, but you didn't actually use them right, such that you ended up having to pass a dirty string to parseInt() and extract the last character the harder way.

          • You neglected to scope match, such that it acts as a global variable. The regex-matching statement is written twice; the assignment could be done within the loop condition instead.

          • The if statements should be an if-else chain, since the conditions are mutually exclusive. However, since the branches are all so similar, a lookup table would be more elegant.




          function durationSeconds(timeExpr)

          var units = 'h': 3600, 'm': 60, 's': 1;
          var regex = /(d+)([hms])/g;

          let seconds = 0;
          var match;
          while ((match = regex.exec(timeExpr)))

          seconds += parseInt(match[1]) * units[match[2]];


          return seconds;


          console.log( durationSeconds("4h12m32s") );





          Alternatively, if you expect that the units will be in the conventional order, you don't have to loop at all.






          function durationSeconds(timeExpr)
          0)
          + 60 * (parseInt(match[2])

          console.log( durationSeconds("4h32s") );








          share|improve this answer











          $endgroup$




          • getValue(str) is such a vague name for the function and its parameter, it could mean anything! Furthermore, "get" implies that this is a getter function that retrieves something, which is not the case.

          • Your regex is ineffective. Capturing parentheses could be useful, but you didn't actually use them right, such that you ended up having to pass a dirty string to parseInt() and extract the last character the harder way.

          • You neglected to scope match, such that it acts as a global variable. The regex-matching statement is written twice; the assignment could be done within the loop condition instead.

          • The if statements should be an if-else chain, since the conditions are mutually exclusive. However, since the branches are all so similar, a lookup table would be more elegant.




          function durationSeconds(timeExpr)

          var units = 'h': 3600, 'm': 60, 's': 1;
          var regex = /(d+)([hms])/g;

          let seconds = 0;
          var match;
          while ((match = regex.exec(timeExpr)))

          seconds += parseInt(match[1]) * units[match[2]];


          return seconds;


          console.log( durationSeconds("4h12m32s") );





          Alternatively, if you expect that the units will be in the conventional order, you don't have to loop at all.






          function durationSeconds(timeExpr)
          0)
          + 60 * (parseInt(match[2])

          console.log( durationSeconds("4h32s") );








          function durationSeconds(timeExpr)

          var units = 'h': 3600, 'm': 60, 's': 1;
          var regex = /(d+)([hms])/g;

          let seconds = 0;
          var match;
          while ((match = regex.exec(timeExpr)))

          seconds += parseInt(match[1]) * units[match[2]];


          return seconds;


          console.log( durationSeconds("4h12m32s") );





          function durationSeconds(timeExpr)

          var units = 'h': 3600, 'm': 60, 's': 1;
          var regex = /(d+)([hms])/g;

          let seconds = 0;
          var match;
          while ((match = regex.exec(timeExpr)))

          seconds += parseInt(match[1]) * units[match[2]];


          return seconds;


          console.log( durationSeconds("4h12m32s") );





          function durationSeconds(timeExpr)
          0)
          + 60 * (parseInt(match[2])

          console.log( durationSeconds("4h32s") );





          function durationSeconds(timeExpr)
          0)
          + 60 * (parseInt(match[2])

          console.log( durationSeconds("4h32s") );






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 6 hours ago

























          answered 7 hours ago









          200_success200_success

          135k21 gold badges172 silver badges442 bronze badges




          135k21 gold badges172 silver badges442 bronze badges























              2












              $begingroup$

              Named Capture Groups



              JavaScript RegExp has named capture groups that can make life a lot simpler when dealing with complicated RegExp. Combined with destructuring assignment you can extract the named hours minutes and seconds as follows.



              function toSeconds(time) 
              const groups: h = 0, m = 0, s = 0 = /(?<h>d*)h(?<m>d*)m(?<s>d*)/i.exec(time);
              return h * 3.6e3 + m * 60 + s * 1; // * 1 to coerce s to Number



              Missing digits are set to zero in the assignment defaults.



              However this is limited to strings that have hours, minutes, and seconds in the correct order (hence no need to match the "s") and will throw an error if there is a problem.



              A more robust solution



              You can also reduce the array created by symbol.matchAll (it returns an iterator that you convert to an array via spread operator)



              It RegExp[symbol.matchAll] is the same call as String.matchAll(RegExp)



              To handle as many variations as possible you can convert the time string to lowercase, soak up white spaces, allow for fractions, multiple periods, and negative periods.



              Using an IIF to wrap the periods constant via closure the function looks like



              const toSeconds = (() => 
              const periods = h: 3600, m: 60, s: 1;
              return time => [.../(-*d*.*d*)W*([hms])/g[Symbol.matchAll](time.toLowerCase())]
              .reduce((time, [, digits, type]) => periods[type] * digits + time, 0);
              )();


              Or via the string



              const toSeconds = (() => 
              const periods = h: 3600, m: 60, s: 1;
              return time => [...time.toLowerCase().matchAll(/(-*d*.*d*)W*([hms])/g)]
              .reduce((time, [, digits, type]) => periods[type] * digits + time, 0);
              )();


              The snippet below shows some of the results of a variety of inputs.






              const toSeconds = (() => 
              const periods = h: 3600, m: 60, s: 1;
              return time => [.../(-*d*.*d*)W*([hms])/g[Symbol.matchAll](time.toLowerCase())]
              .reduce((time, [, digits, type]) =>periods[type] * digits + time, 0);
              )();



              "1h,1m,1s,1,,1s2m3h,3h2m1s,2H2M2S,1h 1H1s1 S1m1M,1.1s,1.2s,s,1h-5m,1 1s,hms"
              .split(",")
              .forEach(time => log(""" + time + "" =" , toSeconds(time)+" seconds"));

              function log(...data)
              document.body.appendChild(
              Object.assign(
              document.createElement("div"), textContent: data.join(" ")
              )
              )





              BTW in Javascript we put...



              • the opening { on the same line as the statement,

              • use camelCase for naming.

              And from many years of C style language experience I would advise you to always delimit statement blocks with eg Bad if (foo) bar = foo, Good if (foo) bar = foo






              share|improve this answer









              $endgroup$

















                2












                $begingroup$

                Named Capture Groups



                JavaScript RegExp has named capture groups that can make life a lot simpler when dealing with complicated RegExp. Combined with destructuring assignment you can extract the named hours minutes and seconds as follows.



                function toSeconds(time) 
                const groups: h = 0, m = 0, s = 0 = /(?<h>d*)h(?<m>d*)m(?<s>d*)/i.exec(time);
                return h * 3.6e3 + m * 60 + s * 1; // * 1 to coerce s to Number



                Missing digits are set to zero in the assignment defaults.



                However this is limited to strings that have hours, minutes, and seconds in the correct order (hence no need to match the "s") and will throw an error if there is a problem.



                A more robust solution



                You can also reduce the array created by symbol.matchAll (it returns an iterator that you convert to an array via spread operator)



                It RegExp[symbol.matchAll] is the same call as String.matchAll(RegExp)



                To handle as many variations as possible you can convert the time string to lowercase, soak up white spaces, allow for fractions, multiple periods, and negative periods.



                Using an IIF to wrap the periods constant via closure the function looks like



                const toSeconds = (() => 
                const periods = h: 3600, m: 60, s: 1;
                return time => [.../(-*d*.*d*)W*([hms])/g[Symbol.matchAll](time.toLowerCase())]
                .reduce((time, [, digits, type]) => periods[type] * digits + time, 0);
                )();


                Or via the string



                const toSeconds = (() => 
                const periods = h: 3600, m: 60, s: 1;
                return time => [...time.toLowerCase().matchAll(/(-*d*.*d*)W*([hms])/g)]
                .reduce((time, [, digits, type]) => periods[type] * digits + time, 0);
                )();


                The snippet below shows some of the results of a variety of inputs.






                const toSeconds = (() => 
                const periods = h: 3600, m: 60, s: 1;
                return time => [.../(-*d*.*d*)W*([hms])/g[Symbol.matchAll](time.toLowerCase())]
                .reduce((time, [, digits, type]) =>periods[type] * digits + time, 0);
                )();



                "1h,1m,1s,1,,1s2m3h,3h2m1s,2H2M2S,1h 1H1s1 S1m1M,1.1s,1.2s,s,1h-5m,1 1s,hms"
                .split(",")
                .forEach(time => log(""" + time + "" =" , toSeconds(time)+" seconds"));

                function log(...data)
                document.body.appendChild(
                Object.assign(
                document.createElement("div"), textContent: data.join(" ")
                )
                )





                BTW in Javascript we put...



                • the opening { on the same line as the statement,

                • use camelCase for naming.

                And from many years of C style language experience I would advise you to always delimit statement blocks with eg Bad if (foo) bar = foo, Good if (foo) bar = foo






                share|improve this answer









                $endgroup$















                  2












                  2








                  2





                  $begingroup$

                  Named Capture Groups



                  JavaScript RegExp has named capture groups that can make life a lot simpler when dealing with complicated RegExp. Combined with destructuring assignment you can extract the named hours minutes and seconds as follows.



                  function toSeconds(time) 
                  const groups: h = 0, m = 0, s = 0 = /(?<h>d*)h(?<m>d*)m(?<s>d*)/i.exec(time);
                  return h * 3.6e3 + m * 60 + s * 1; // * 1 to coerce s to Number



                  Missing digits are set to zero in the assignment defaults.



                  However this is limited to strings that have hours, minutes, and seconds in the correct order (hence no need to match the "s") and will throw an error if there is a problem.



                  A more robust solution



                  You can also reduce the array created by symbol.matchAll (it returns an iterator that you convert to an array via spread operator)



                  It RegExp[symbol.matchAll] is the same call as String.matchAll(RegExp)



                  To handle as many variations as possible you can convert the time string to lowercase, soak up white spaces, allow for fractions, multiple periods, and negative periods.



                  Using an IIF to wrap the periods constant via closure the function looks like



                  const toSeconds = (() => 
                  const periods = h: 3600, m: 60, s: 1;
                  return time => [.../(-*d*.*d*)W*([hms])/g[Symbol.matchAll](time.toLowerCase())]
                  .reduce((time, [, digits, type]) => periods[type] * digits + time, 0);
                  )();


                  Or via the string



                  const toSeconds = (() => 
                  const periods = h: 3600, m: 60, s: 1;
                  return time => [...time.toLowerCase().matchAll(/(-*d*.*d*)W*([hms])/g)]
                  .reduce((time, [, digits, type]) => periods[type] * digits + time, 0);
                  )();


                  The snippet below shows some of the results of a variety of inputs.






                  const toSeconds = (() => 
                  const periods = h: 3600, m: 60, s: 1;
                  return time => [.../(-*d*.*d*)W*([hms])/g[Symbol.matchAll](time.toLowerCase())]
                  .reduce((time, [, digits, type]) =>periods[type] * digits + time, 0);
                  )();



                  "1h,1m,1s,1,,1s2m3h,3h2m1s,2H2M2S,1h 1H1s1 S1m1M,1.1s,1.2s,s,1h-5m,1 1s,hms"
                  .split(",")
                  .forEach(time => log(""" + time + "" =" , toSeconds(time)+" seconds"));

                  function log(...data)
                  document.body.appendChild(
                  Object.assign(
                  document.createElement("div"), textContent: data.join(" ")
                  )
                  )





                  BTW in Javascript we put...



                  • the opening { on the same line as the statement,

                  • use camelCase for naming.

                  And from many years of C style language experience I would advise you to always delimit statement blocks with eg Bad if (foo) bar = foo, Good if (foo) bar = foo






                  share|improve this answer









                  $endgroup$



                  Named Capture Groups



                  JavaScript RegExp has named capture groups that can make life a lot simpler when dealing with complicated RegExp. Combined with destructuring assignment you can extract the named hours minutes and seconds as follows.



                  function toSeconds(time) 
                  const groups: h = 0, m = 0, s = 0 = /(?<h>d*)h(?<m>d*)m(?<s>d*)/i.exec(time);
                  return h * 3.6e3 + m * 60 + s * 1; // * 1 to coerce s to Number



                  Missing digits are set to zero in the assignment defaults.



                  However this is limited to strings that have hours, minutes, and seconds in the correct order (hence no need to match the "s") and will throw an error if there is a problem.



                  A more robust solution



                  You can also reduce the array created by symbol.matchAll (it returns an iterator that you convert to an array via spread operator)



                  It RegExp[symbol.matchAll] is the same call as String.matchAll(RegExp)



                  To handle as many variations as possible you can convert the time string to lowercase, soak up white spaces, allow for fractions, multiple periods, and negative periods.



                  Using an IIF to wrap the periods constant via closure the function looks like



                  const toSeconds = (() => 
                  const periods = h: 3600, m: 60, s: 1;
                  return time => [.../(-*d*.*d*)W*([hms])/g[Symbol.matchAll](time.toLowerCase())]
                  .reduce((time, [, digits, type]) => periods[type] * digits + time, 0);
                  )();


                  Or via the string



                  const toSeconds = (() => 
                  const periods = h: 3600, m: 60, s: 1;
                  return time => [...time.toLowerCase().matchAll(/(-*d*.*d*)W*([hms])/g)]
                  .reduce((time, [, digits, type]) => periods[type] * digits + time, 0);
                  )();


                  The snippet below shows some of the results of a variety of inputs.






                  const toSeconds = (() => 
                  const periods = h: 3600, m: 60, s: 1;
                  return time => [.../(-*d*.*d*)W*([hms])/g[Symbol.matchAll](time.toLowerCase())]
                  .reduce((time, [, digits, type]) =>periods[type] * digits + time, 0);
                  )();



                  "1h,1m,1s,1,,1s2m3h,3h2m1s,2H2M2S,1h 1H1s1 S1m1M,1.1s,1.2s,s,1h-5m,1 1s,hms"
                  .split(",")
                  .forEach(time => log(""" + time + "" =" , toSeconds(time)+" seconds"));

                  function log(...data)
                  document.body.appendChild(
                  Object.assign(
                  document.createElement("div"), textContent: data.join(" ")
                  )
                  )





                  BTW in Javascript we put...



                  • the opening { on the same line as the statement,

                  • use camelCase for naming.

                  And from many years of C style language experience I would advise you to always delimit statement blocks with eg Bad if (foo) bar = foo, Good if (foo) bar = foo






                  const toSeconds = (() => 
                  const periods = h: 3600, m: 60, s: 1;
                  return time => [.../(-*d*.*d*)W*([hms])/g[Symbol.matchAll](time.toLowerCase())]
                  .reduce((time, [, digits, type]) =>periods[type] * digits + time, 0);
                  )();



                  "1h,1m,1s,1,,1s2m3h,3h2m1s,2H2M2S,1h 1H1s1 S1m1M,1.1s,1.2s,s,1h-5m,1 1s,hms"
                  .split(",")
                  .forEach(time => log(""" + time + "" =" , toSeconds(time)+" seconds"));

                  function log(...data)
                  document.body.appendChild(
                  Object.assign(
                  document.createElement("div"), textContent: data.join(" ")
                  )
                  )





                  const toSeconds = (() => 
                  const periods = h: 3600, m: 60, s: 1;
                  return time => [.../(-*d*.*d*)W*([hms])/g[Symbol.matchAll](time.toLowerCase())]
                  .reduce((time, [, digits, type]) =>periods[type] * digits + time, 0);
                  )();



                  "1h,1m,1s,1,,1s2m3h,3h2m1s,2H2M2S,1h 1H1s1 S1m1M,1.1s,1.2s,s,1h-5m,1 1s,hms"
                  .split(",")
                  .forEach(time => log(""" + time + "" =" , toSeconds(time)+" seconds"));

                  function log(...data)
                  document.body.appendChild(
                  Object.assign(
                  document.createElement("div"), textContent: data.join(" ")
                  )
                  )






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 40 mins ago









                  Blindman67Blindman67

                  12.5k1 gold badge6 silver badges25 bronze badges




                  12.5k1 gold badge6 silver badges25 bronze badges



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Code Review Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      Use MathJax to format equations. MathJax reference.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f224931%2fconvert-a-string-like-4h53m12s-to-a-total-number-of-seconds-in-javascript%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      ParseJSON using SSJSUsing AMPscript with SSJS ActivitiesHow to resubscribe a user in Marketing cloud using SSJS?Pulling Subscriber Status from Lists using SSJSRetrieving Emails using SSJSProblem in updating DE using SSJSUsing SSJS to send single email in Marketing CloudError adding EmailSendDefinition using SSJS

                      Кампала Садржај Географија Географија Историја Становништво Привреда Партнерски градови Референце Спољашње везе Мени за навигацију0°11′ СГШ; 32°20′ ИГД / 0.18° СГШ; 32.34° ИГД / 0.18; 32.340°11′ СГШ; 32°20′ ИГД / 0.18° СГШ; 32.34° ИГД / 0.18; 32.34МедијиПодациЗванични веб-сајту

                      19. јануар Садржај Догађаји Рођења Смрти Празници и дани сећања Види још Референце Мени за навигацијуу