I want to parse text messages contained in a template string to the following JS object. Every text message is seperated by a new line and after the authors name there is a colon. The content of the message can also include new lines, square brackets and colons. What is your preferred way of solving this?
let string = `[03.12.21, 16:12:52] John Doe: Two questions:
How are you? And is lunch at 7 fine?
[03.12.21, 16:14:30] Jane Doe: Im fine. 7 sounds good.`;
let data = {
"03.12.21, 16:12:52": {
"author": "John Doe",
"content": "Two questions:\nHow are you? And is lunch at 7 fine?"
},
"03.12.21, 16:14:30": {
"author": "John Doe",
"content": "Im fine. 7 sounds good."
},
}; // will be parseString()
function parseString() {
// ?
}
CodePudding user response:
like this?
let string = `[03.12.21, 16:12:52] John Doe: Two questions:
How are you? And is lunch at 7 fine?
[03.12.21, 16:14:30] Jane Doe: Im fine. 7 sounds good.`;
let chunks = string.split(/^\[(\d\d\.\d\d\.\d\d, \d\d\:\d\d\:\d\d)\](.*?):/m);
let data = {};
for (let i = 3; i < chunks.length; i = 3) {
const date = chunks[i - 2];
const author = chunks[i - 1].trim();
const content = chunks[i].trim();
data[date] = {
author,
content,
};
}
console.log(data);
.as-console-wrapper{top:0;max-height:100%!important}
CodePudding user response:
I would split the to whole string into little pieces like: let string = date author content. With that its much simpler. Or use something like string.split()
CodePudding user response:
Something like this?
function parseMessage(message) {
var messageObj = {};
var messageArray = message.split(" ");
messageObj.command = messageArray[0];
messageObj.args = messageArray.slice(1);
return messageObj;
}