My substr method not working in js

What is the difference between the uncommented lines vs the commented(which is grabbing mm and multiplying by 60 then concatenating with ss)?

function getSeconds(str) {
  // var mm = str.substr(0,2);
  // var ss = str.substr(3,5);
  // return mm*60+ss;
  var nums = str.split(':'),
    mm = +nums[0],
    ss = +nums[1];
  return mm * 60 + ss;
}

getSeconds("13:25");

22 thoughts on “My substr method not working in js”

  1. In the working example, you are explicitly converting the strings into numbers using the + prefix.

    In the commented out example, you are not. The minutes are implicitly converted into a number due to the multiplication, however the seconds are simply appended via a string concatenation.

    You can resolve that by explicitly converting the two components this example as well:

    function getSeconds(str) {
      var mm = +str.substr(0,2);
      var ss = +str.substr(3,2);
      return mm*60+ss;
    }
    
    console.log(getSeconds("13:25"));
    Reply

Leave a Comment