Here’s another suggestion. Treating data this way is always risky because it can infiltrate errors. But here it is:
var texto = document.body.innerHTML.split('\n').filter(Boolean); // só para o exemplo do jsFiddle ir buscar texto
var linhas = texto.map(function(linha) {
if (linha.match(/^\s+$/)) return; // linhas vazias
linha = linha.split(/^\s+|\s+$/).join(''); // limpa linhas que começam ou acabam com espaços
return linha.split(/[\s]{2,}/);
}).filter(Boolean);
var campos = ['nome', 'rg', 'data', 'value'];
var lista = {};
campos.forEach(function(campo, i) {
lista[campo] = []; // criar a array para cada campo
linhas.forEach(function(linha) {
lista[campo].push(linha[i]); // adicionar valor à array
});
});
console.log(lista);
Upshot:
{
"nome": ["Carlos Alberto", "Juliano Fontes", "Carlos ALberto"],
"rg": ["xxxxxxx", "xxxxxxx", "xxxxxxx"],
"data": ["11/02/2016", "12/02/2016", "13/02/2016"],
"value": ["$103.10", "$102.10", "$500.00"]
}
If you have that text in a variable just replace:
var texto = document.body.innerHTML.split('\n').filter(Boolean);
for:
var texto = tuaVariavel.split('\n').filter(Boolean);
Hello, Have an array [] or JSON {}? Between data will always have 2 spaces " "?
– Tiago Gomes
You can give an example of the result you want to get?
– Sergio
Hello, it’s a list of objects I’m going to use to fill a table, so it would be a json. var lista = { nome[], rg[], data[],value[]}; I want to fill in as a simple list for popular in a table.
– War Lock
The spaces will always be 2.
– War Lock
Do you mean the spaces between fields of each line? Will they always be 2? (Because in your example are more than two spaces between fields)
– Sergio
@Sergio is right. Are there always 2 spaces and all the data? (even between lines)
– Tiago Gomes