计算段落内的单词,里面有HTML标签

时间:2017-03-15 00:57:33

标签: javascript jquery html

我正在寻找如何计算某些元素中的单词,并且我成功地得到了以下内容:



var text = $("p").text();

// split() deals with multiple spaces, tabs and new lines.
var wordsCount = text.trim().split( /\s+/ ).length;

$("p").append("<br>Words: <b> " + wordsCount + "</b>");
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="p-1">These are some texts just for demo purpose</p>
&#13;
&#13;
&#13;

但如果段落中包含HTML标签,则如下所示:

<p class="p-1">These are <span>some texts</span> just for demo purpose</p>

<p class="p-1">These are <span>some <strong>texts</strong></span> just for demo purpose</p>

然后它会假设<span>some是单个字符串,尽管它应该将some计为第3个字。

另外例如如何根据我要求的计数来包装第3或第4个单词?

2 个答案:

答案 0 :(得分:0)

您可以使用.contents()jquery方法

jquery documentation

这是一个小例子

    $( "p" )
  .contents()
  .filter(function(){
    console.log($(this))
    var wordsCount = $(this).text().trim().split( /\s+/ ).length;

$("p").append("<br>Words: <b> " + wordsCount + "</b>");
    return this.nodeType !== 1;
  })

jsfidle

$( "p" )
  .contents()
  .filter(function(){
  	console.log($(this))
    var wordsCount = $(this).text().trim().split( /\s+/ ).length;

$("p").append("<br>Words: <b> " + wordsCount + "</b>");
    return this.nodeType !== 1;
  })
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<p class="p-1">These are <span>some <strong>texts</strong></span> just for demo purpose</p>

答案 1 :(得分:0)

试试这个codepen.io或者您愿意:

&#13;
&#13;
 $('p').each(function(i, element) {
  element.innerHTML = element.innerHTML.split(/\s+/g).map(function(word) {
      return '<span>'+word+'</span>';
  }).join(' ');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="p-1">These are some texts just for demo purpose</p>
<p class="p-1">These are <span>some texts</span> just for demo purpose</p>
<p class="p-1">These are <span>some <strong>texts</strong></span> just for demo purpose</p>
&#13;
&#13;
&#13;

或者取决于你想要的东西:

&#13;
&#13;
 $("p").each(function(i, element) {
  var text = element.innerHTML;

  // split() deals with multiple spaces, tabs and new lines.
  var wordsCount = text.trim().split( /\w+/ ).length -1;

  element.innerHTML += "<br>Words: <b> " + wordsCount + "</b>";
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="p-1">These are some texts just for demo purpose</p>
<p class="p-1">These are <span>some texts</span> just for demo purpose</p>
<p class="p-1">These are <span>some <strong>texts</strong></span> just for demo purpose</p>
&#13;
&#13;
&#13;