julian julian - 1 year ago 137
Javascript Question

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;


Answer Source

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,5);
  return mm*60+ss;

console.log(getSeconds("13: 25"));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download