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.',
''
]
3 Answers 3
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);
6 Comments
filter to remove that key from the array.\n\n in the input. Just added a quick little shorthand for removing empty strings from the array :)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)
Comments
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