Skip to content
Advertisement

Adding strings returns empty string in Javascript

My goal is for this function to return only “03.12.21, 16:12:52”. Currently only “]” is returned.

let txt = `[03.12.21, 16:12:52] Firstname Lastname: Some text [03.12.21, 16:14:30] Firstname Lastname: Some text`;

console.log(parseDate()); // "]"

function parseDate() {
  for (let i = 0; i < txt.length; i++) {
    let char = txt[i];
    let date = "";
    date += char;
    if (char === "]") {
      return date;
    }
  }
}

Advertisement

Answer

Move let date = ""; outside of the loop (you are resetting it each iteration)

let txt = `[03.12.21, 16:12:52] First Name: Some text [03.12.21, 16:14:30] Felix Krückel: Some text`;

console.log(parseDate()); // "]"

function parseDate() {
  let date = "";
  for (let i = 0; i < txt.length; i++) {
    let char = txt[i];
    date += char;
    if (char === "]") {
      return date;
    }
  }
}
Advertisement