Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
How can I parse a string of text messages into an object

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() {
  // ?
}

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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}

about 4 years ago · Juan Pablo Isaza Relatório

0

Something like this?

function parseMessage(message) {
   var messageObj = {};
   var messageArray = message.split(" ");
   messageObj.command = messageArray[0];
   messageObj.args = messageArray.slice(1);
   return messageObj;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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()

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda