javascript split(" \ n \ r")在空行上添加逗号

时间:2017-06-21 05:11:50

标签: javascript split newline

我有以下代码导入文件。我用split(" \ n \ r")代码拆分它,但现在每个空行都有逗号。如何修复..请参阅下面的代码并输出图片。

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    </head>

<body>


        <textarea id="textareaid" name="textareaid" class = "textdata" value="" rows="10" cols="100" placeholder="Enter Any Text!"></textarea>
        <br>
        <input id="filename"  class="btnsubmit"  type="file" accept="text/plain" onchange="PreviewText();"  />

<script type="text/javascript">

              function PreviewText() {
                var file = document.getElementById("filename").files[0];
                    var reader = new FileReader();
                    reader.onload = function (e) {
                    var array = e.target.result.split("\n\r");
                    alert (array);
                    document.getElementById("textareaid").value = array;
                    };
                    reader.readAsText(file);
        };

</script>

</body>
</html>

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以在textarea中显示所有只有逗号的行。

检查以下代码段。我使用Array.filter检查该行是否有,

&#13;
&#13;
var array = [
  "Hello",
  ",",
  "Something",
  ",",
  "Great"
];

array = array.filter(function(line) {
  return line.length > 1 && line !== ",";
});

console.log(array);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

为什么不这样做,Array.join(" ")将数组转换为字符串并删除分隔符,在本例中,数组为逗号

检查出来:

          function PreviewText() {
                var file = document.getElementById("filename").files[0];
                var reader = new FileReader();
                reader.onload = function (e) {

                var array = e.target.result.split("\n\r");
                document.getElementById("textareaid").value = array[0]
                document.getElementById("textareaid1").value = array[1]
                document.getElementById("textareaid2").value = array[2]
                };
                reader.readAsText(file);  // 
    };

========================================== // === =======================

如果你想动态地这样做,你可以这样做:

array.forEach(function(article){
  list = document.createElement("ul");
  line = document.createElement("li");
  span = document.createElement("span");

  art = document.createTextNode(article) 

  span.appendChild(art);
  line.appendChild(span);
  list.appendChild(line);

  boxNode.appendChild(list)
})

工作示例(概念证明) https://jsbin.com/fuyirajoni/edit?html,js,output

希望它可以帮到你:)