如何使用split将文本转换为数组

时间:2016-11-19 12:22:36

标签: javascript html css

我想使用split 将文本转换为数组,并且显示div中数组的最后一行(名为result)。我的问题是如何在textarea中使用它检测到的转义序列\ n在javascript中,所以它转换为数组

 var txtBox = document.getElementById("textArea");
    var lines = txtBox.value.split("\n");
    // print out last line to page
    var blk = document.getElementById("result");
    blk.innerHTML = lines[lines.length - 1];

<textarea id="textArea" style="width: 710px;color: #ffffff;background: activecaption">
     On the other hand,<br/>
     we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of 
</textarea>

1 个答案:

答案 0 :(得分:0)

看起来你错过了trim()方法。所以你的最后一个数组就是&#34;&#34; (空字符串)。请查看这个

&#13;
&#13;
var txtBox = document.getElementById("textArea");
//you need to trim your string to avoid your array item contains "" null string
var lines = txtBox.value.trim().split("\n");
// print out last line to page
var blk = document.getElementById("result");
blk.innerHTML = lines[lines.length - 1];
console.log("Array length: " + lines.length);
&#13;
<textarea id="textArea" style="width: 710px;color: #ffffff;background: activecaption">
  On the other hand, <!--no need `<br\>` in text area-->
  we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of
</textarea>
<hr>
<div id="result">

</div>
&#13;
&#13;
&#13;

相关问题