Rafael Lima
Rafael Lima

Reputation: 420

Format string into an array

I have this string:

var comments = "2020-01-15 15:06:53 - Rafael Souza (Comentários adicionais)\nTESTE: Comentários adicionais.\n\n2020-01-15 14:47:39 - Rafael Souza (Comentários adicionais)\nChecado problema no servidor.\n\n";

console.log(comments);
2020-01-15 15:06:53 - Rafael Souza (Comentários adicionais)
TESTE: Comentários adicionais.

2020-01-15 14:47:39 - Rafael Souza (Comentários adicionais)
Checado problema no servidor.

I would like to format to an array, like this: The length of this array can increase or decrease.

['2020-01-15 15:06:53 - Rafael Souza (Comentários adicionais) TESTE: Comentários adicionais.', '2020-01-15 14:47:39 - Rafael Souza (Comentários adicionais) Checado problema no servidor.']

I tried with this command, but I didn't have the desired result.

console.log(comments.split('\n'));
[
  '2020-01-15 15:06:53 - Rafael Souza (Comentários adicionais)\n' +
    'TESTE: Comentários adicionais.',
  '2020-01-15 14:47:39 - Rafael Souza (Comentários adicionais)\n' +
    'Checado problema no servidor.',
  ''
]

Upvotes: 1

Views: 71

Answers (3)

ofundefined
ofundefined

Reputation: 3309

Mind performance:

.split() accepts regex:

Use comments.split(/[\n]{2}[^$]/)

Which is equivalent to comments.split(/\n\n[^$]/)

It will split the string using \n\n\ as a patter except when $ (end of line) follows it.

Just a piece of information:

If separator appears at the beginning or end of the string, or both, the array begins, ends, or both begins and ends, respectively, with an empty string.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191946

Make a non greedy match of a sequence of space and non space characters [\S\s]+?, that has a sequence of two \n after it (?=\n{2}). Afterwards replace the remaining \n to spaces.

var comments = "2020-01-15 15:06:53 - Rafael Souza (Comentários adicionais)\nTESTE: Comentários adicionais.\n\n2020-01-15 14:47:39 - Rafael Souza (Comentários adicionais)\nChecado problema no servidor.\n\n";

var result = comments.match(/[\S\s]+?(?=\n{2})/g)
  .map(str => str.replace(/\n/g, ' '))

console.log(result)

Upvotes: 1

IceMetalPunk
IceMetalPunk

Reputation: 5556

Looks like what you really want is to split at double line breaks, then remove the single line breaks from inside each entry.

comments.split('\n\n').map(comment => comment.replace(/\n/g, ' ')).filter(comment => comment);

Upvotes: 5

Related Questions