将文本拆分为数组

时间:2016-11-16 16:51:59

标签: javascript html css3

我想在文本区域(inputbox div)中拆分文本(转换为数组)并在名为result的div id中显示它们?



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

<div id="result"></div>
<div id="singleQuote"></div>
<div id="inputbox" 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
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

请查看此内容。您需要将value更改为innerText。这是因为您正在访问div而不是input

var txtBox = document.getElementById("inputbox");
var lines = txtBox.innerText.split("\n");
// print out last line to page
var blk = document.getElementById("result");
blk.innerHTML = lines[lines.length - 1];
<div id="result"></div>
<div id="singleQuote"></div>
<div id="inputbox" 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
</div>

答案 1 :(得分:0)

在我看来,您试图分开\n而不是\n\r\r\n ... 另一个奇怪的是,它只适用于innerText;)

var txtBox = document.getElementById("inputbox");
var lines = txtBox.innerText.split(/[\n\r]/g);

// print out last line to page
var blk = document.getElementById("result");
blk.innerHTML = lines[lines.length - 1];
#result {
  background-color: green;
}

#inputbox {
  background-color: black;
  color: white;
}
<div id="result"></div>
<div id="singleQuote"></div>
<div id="inputbox">
  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
</div>

答案 2 :(得分:0)

使用 split() javascript函数。

例如

str = "abc\ndef";
console.log(str.split("\n"));

将打印出来

["abc", "def"]