Tally字符串出现在div中的次数

时间:2018-05-10 19:15:49

标签: javascript html arrays sum

我有以下简单< html>页面突出了' @'图标显示在< div>

中的OnLoaded .txt文件中

我想知道的是......我怎么能算出' @' @'字符串出现在< div>中?



var openFile = function(event) {
  var input = event.target;
  var reader = new FileReader();
  reader.onload = function() {
    var text = reader.result;
    var output = document.getElementById('output');
    
    const lines = text.split('\n');
    lines.forEach((line) => {
      const div = output.appendChild(document.createElement('div'));
      const textSplitAroundAt = line.split('@');
      textSplitAroundAt.forEach((text, i) => {
        div.appendChild(document.createTextNode(text));
        if (i === textSplitAroundAt.length - 1) return;
        const span = div.appendChild(document.createElement('span'));
        span.textContent = '@';
        span.className = 'colorize';
      });

    });
  };
  reader.readAsText(input.files[0]);
};

.colorize
{
	color: #f90;
	background-color: blue;
}

<center>
  <h1>.TXT Log Parser</h1>
</center>

<center>
  <div id="populateNumbers">I would like the number of times '@' symbol appears here >>> ... </div> 
</center>	

<center>
  <h2><input type='file' accept='text/plain' onchange='openFile(event)'></h2>
</center>
<br/>
<div id='output'>...</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

onload活动结束时添加此代码:

document.getElementById('populateNumbers').textContent = text.split('@').length - 1;

&#13;
&#13;
var openFile = function(event) {
  var input = event.target;
  var reader = new FileReader();
  reader.onload = function() {
    var text = reader.result;
    var output = document.getElementById('output');
    
    const lines = text.split('\n');
    lines.forEach((line) => {
      const div = output.appendChild(document.createElement('div'));
      const textSplitAroundAt = line.split('@');
      textSplitAroundAt.forEach((text, i) => {
        div.appendChild(document.createTextNode(text));
        if (i === textSplitAroundAt.length - 1) return;
        const span = div.appendChild(document.createElement('span'));
        span.textContent = '@';
        span.className = 'colorize';
      });

    });
    document.getElementById('populateNumbers').textContent = text.split('@').length - 1;
  };
  reader.readAsText(input.files[0]);
};
&#13;
.colorize
{
	color: #f90;
	background-color: blue;
}
&#13;
<center>
  <h1>.TXT Log Parser</h1>
</center>

<center>
  <div>I would like the number of times '@' symbol appears here: <span id="populateNumbers"> ... </span></div> 
</center>	

<center>
  <h2><input type='file' accept='text/plain' onchange='openFile(event)'></h2>
</center>
<br/>
<div id='output'>...</div>
&#13;
&#13;
&#13;