My goal is for this function to return only “03.12.21, 16:12:52”. Currently only “]” is returned.
JavaScript
x
14
14
1
let txt = `[03.12.21, 16:12:52] Firstname Lastname: Some text [03.12.21, 16:14:30] Firstname Lastname: Some text`;
2
3
console.log(parseDate()); // "]"
4
5
function parseDate() {
6
for (let i = 0; i < txt.length; i++) {
7
let char = txt[i];
8
let date = "";
9
date += char;
10
if (char === "]") {
11
return date;
12
}
13
}
14
}
Advertisement
Answer
Move let date = "";
outside of the loop (you are resetting it each iteration)
JavaScript
1
14
14
1
let txt = `[03.12.21, 16:12:52] First Name: Some text [03.12.21, 16:14:30] Felix Krückel: Some text`;
2
3
console.log(parseDate()); // "]"
4
5
function parseDate() {
6
let date = "";
7
for (let i = 0; i < txt.length; i++) {
8
let char = txt[i];
9
date += char;
10
if (char === "]") {
11
return date;
12
}
13
}
14
}