段落中的字母数

时间:2018-03-14 22:14:16

标签: javascript

所以我将段落转换为字符串并尝试计算字母但是......

HTML:

<p id="text">example text a</p>
<p id="example"></p>

的JavaScript

function alert(){
  var str = document.getElementById('text').outerHTML;
var counta = str.match(/a/g).length;
var countd = str.match(/d/g).length;
var county = str.match(/y/g).length;
document.getElementById("example").innerHTML= counta+ " " +countd+ " " + county;
}

我需要计算段落中的每个字母,但我有一个问题。就像下面的例子中一样,我想检查字母“a”,“d”,“y”。在我的例子中,我没有“y”字母和“d”。 那么为什么我的输出像2 1 1?哪里弄错了?? !!

4 个答案:

答案 0 :(得分:1)

您正在获取outerHTML,其中包含标记信息(<p id="text">)。这就是你有一个d(id)的原因。

使用innerHTML获取代码之间的内容。您甚至可能希望使用innerText,因此它会忽略内部的标记,我修改了您的示例以包含<span>来说明这一点。

&#13;
&#13;
function getCount(matchResult) {
  return matchResult ? matchResult.length : 0;
}

var innerHTML = document.getElementById('text').innerHTML;
   
var counta = getCount(innerHTML.match(/a/g));
var countd = getCount(innerHTML.match(/d/g));
var county = getCount(innerHTML.match(/y/g));

document.getElementById("exampleInnerHTML").innerHTML = counta + " " + countd + " " + county;

var innerText = document.getElementById('text').innerText;

counta = getCount(innerText.match(/a/g));
countd = getCount(innerText.match(/d/g));
county = getCount(innerText.match(/y/g));

document.getElementById("exampleInnerText").innerHTML = counta + " " + countd + " " + county;
&#13;
<p id="text">example text <span>a</span></p>
<h2>Using innerHTML</h2>
<p id="exampleInnerHTML"></p>
<h2>Using innerText</h2>
<p id="exampleInnerText"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

因为您使用的是outerHTML,所以得到2 1 1。 outerHTML将为您提供整个代码及其内容,在本例中为<p id="text">example text a</p>,因此您可能希望使用innerHTML来仅对实际内容进行匹配。

答案 2 :(得分:0)

首先,您应该使用innerHTML而不是outerHTML。 此外,您应该重命名您的函数,因为您正在覆盖JS alert函数。

但是,您遇到的问题是.match如果找不到匹配则返回null。因此,您需要为计数变量设置默认值。

尝试这样的事情:

function count(){
  var str = document.getElementById('text').innerHTML;
  var matcha = str.match(/a/g);
  var matchd = str.match(/d/g);
  var matchy = str.match(/y/g);
  var counta = matcha ? matcha.length : 0;
  var countd = matchd ? matchd.length : 0;
  var county = matchy ? matchy.length : 0;
  document.getElementById("example").innerHTML= counta+ " " +countd+ " " + county;
}

答案 3 :(得分:0)

确保您只使用.textContent或类似的JS库方法(.outerHTML拉入您的html标记和属性)来获取元素的文本内容。这应该可以解决问题。

使用.innerHTML可能会有问题,因为该方法将像outerHTML一样返回任何嵌入的HTML标记和属性。例如,我在文本周围添加了一个范围。在id为&#34; text&#34;的元素上使用.innerHTML会返回span标签和文本。使用.textContent将仅返回文本节点的内容。

&#13;
&#13;
function alert(){
  var str = document.getElementById("text").textContent;
  console.log(str); 
  
  var counta = str.match(/a/g).length;
  var countb = str.match(/b/g).length;
  
  console.log(str.match(/a/g));
  console.log(str.match(/b/g));
  
  console.log(counta);
  console.log(countb);
  
  var newStr = document.getElementById("text").innerHTML;
  console.log(newStr);
}

alert();
&#13;
<p id="text"><span>an example text for the letters a and b</span></p>
<p id="example"></p>
&#13;
&#13;
&#13;