Skip to main content
remove commas from output strings in description
Source Link

I have a function that takes a time of minutes and seconds, and converts it to a string in the following way: '0:30' would become '30 Seconds', '1:30' would become '1 minute, 30 seconds', '2:01' would become '2 minutes, 1 second', etc. My function works fine, but I'm wondering if there are areas for improvement.

function formatTime(formattedTime) {
  let minStr, secStr;
  let minNum = formattedTime.split(':')[0];
  let secNum = formattedTime.split(':')[1];
  if (minNum === '1') {
    minStr = 'minute';
  } else {
    minStr = 'minutes';
  }
  if (secNum === '01') {
    secStr = 'second';
    secNum = '1';
  } else {
    secStr = 'seconds';
  }
  if (minNum === '0') {
    return `${secNum} ${secStr}`;
  } else if (secNum === '00') {
    return `${minNum} ${minStr}`;
  } else {
    return `${minNum} ${minStr} ${secNum} ${secStr}`;
 }
}

I have a function that takes a time of minutes and seconds, and converts it to a string in the following way: '0:30' would become '30 Seconds', '1:30' would become '1 minute, 30 seconds', '2:01' would become '2 minutes, 1 second', etc. My function works fine, but I'm wondering if there are areas for improvement.

function formatTime(formattedTime) {
  let minStr, secStr;
  let minNum = formattedTime.split(':')[0];
  let secNum = formattedTime.split(':')[1];
  if (minNum === '1') {
    minStr = 'minute';
  } else {
    minStr = 'minutes';
  }
  if (secNum === '01') {
    secStr = 'second';
    secNum = '1';
  } else {
    secStr = 'seconds';
  }
  if (minNum === '0') {
    return `${secNum} ${secStr}`;
  } else if (secNum === '00') {
    return `${minNum} ${minStr}`;
  } else {
    return `${minNum} ${minStr} ${secNum} ${secStr}`;
 }
}

I have a function that takes a time of minutes and seconds, and converts it to a string in the following way: '0:30' would become '30 Seconds', '1:30' would become '1 minute 30 seconds', '2:01' would become '2 minutes 1 second', etc. My function works fine, but I'm wondering if there are areas for improvement.

function formatTime(formattedTime) {
  let minStr, secStr;
  let minNum = formattedTime.split(':')[0];
  let secNum = formattedTime.split(':')[1];
  if (minNum === '1') {
    minStr = 'minute';
  } else {
    minStr = 'minutes';
  }
  if (secNum === '01') {
    secStr = 'second';
    secNum = '1';
  } else {
    secStr = 'seconds';
  }
  if (minNum === '0') {
    return `${secNum} ${secStr}`;
  } else if (secNum === '00') {
    return `${minNum} ${minStr}`;
  } else {
    return `${minNum} ${minStr} ${secNum} ${secStr}`;
 }
}
[Edit removed during grace period]
Link
edited title
Link

Formatting mm:ss to string with Javascript

deleted 8 characters in body; edited tags; edited title
Source Link
Jamal
  • 35.2k
  • 13
  • 134
  • 238
Loading
Source Link
Loading