Change txt column

0

I need to change the contents of a column with javascript, so I do not need to use php with apache. Since I would run with html and javascript.

It would be a file with 10 columns and would only modify the 5th column and that only the cell that had blank.

1|1|1|1| |1|1|1|1|1|

The file would be set by the form and would change the 5th column that was blank with content from a text field of the form.

And do this for the next few lines of the same text.

    
asked by anonymous 28.06.2016 / 17:30

1 answer

1

What you can do in Javascript is a method that changes the content:

var content = '1|1|1|1| |1|1|1|1|1|';

 alterContent(content, '123');
 function alterContent(content, val) {
 var add = [];
    content.split('|').forEach(function(v, e){
      add[e] = (e == 4 && (v == ' '|| v == '')) ? val : v;
    });
    return add.join('|');
 }

If you need to do this for each line, just pass the method inside a loop and test each line:

var content =  "1|1|1|1| |1|1|1|1|1|\n1|1|1|1| |1|1|1|1|1|\n1|1|1|1|1|1|1|1|1|1|";
var linhas = content.split("\n");

/* passa a posição 2, se usar parâmetro: null,
   ignora a regra de linha, e testa todas as linhas */
alterarLinhas(linhas, '123', 2);

function alterarLinhas(linhas, val, posicao_linha) {
    for (var i=0; i <= linhas.length; i++) {
        if (posicao_linha != null) {
           if (posicao_linha == i) {
              linhas[i] = alterContent(linhas[i], val);
           } else {
              linhas[i] = val;
           }
        } else {
           linhas[i] = alterContent(linhas[i], val);
        }
    }
return linhas.join("\n");
}

function alterContent(content, val) {
    var add = [];
    content.split('|').forEach(function(v, e){
          add[e] = (e == 4 && (v == ' '|| v == '')) ? val : v;
    });
    return add.join('|');
}

1st JSFIDDLE example
2nd JSFIDDLE example

How much to read, change and record: see this .

    
28.06.2016 / 19:30