字数jQuery元素

时间:2017-01-13 20:59:34

标签: javascript jquery word-count

我试图从1个元素中获取单词count并将其放入变量中。但我不确定最好的方法。有什么想法吗?

var value = $('#text1').val();

var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;

$('#text1').html(wordCount);

<p id="text1" class="entry">This is test text in this template</p>

我在这个Question中尝试了答案,添加了以下代码并得到了此错误。 TypeError:undefined不是对象(评估'$('#text1')。val()。replace')

var word_count = $('#text1').val().replace(/^[\s,.;]+/, "").replace(/[\s,.;]+$/, "").split(/[\s,.;]+/).length;

<!DOCTYPE html>
    <html>

    <head>
      <title>text_centred</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
      <style type="text/css">
        * {
          margin: 0px;
          padding: 0px;
        }
        html,
        body {
          height: 100%;
          width: 100%;
          overflow: auto;
        }
        body {
          background-position: center;
          background-size: cover;
          background-repeat: no-repeat;
        }
        p {
          font-size: 16px;
          color: #4d4d4d;
          font-family: FrescoSans-Normal;
          text-align: center;
          line-height: 24px;
          padding-bottom: 15px;
          opacity: 1;
        }
        #textBlock {
          height: 100%;
          overflow: auto;
          width: 100%;
        }
        #wrapper {
          position: relative;
          width: 60%;
          margin: 0 auto;
          max-width: 800px;
          height: auto;
        }
      </style>
      <script type="text/javascript">
        var value = $('#text1').text(); //.val() works on inputs, get the text instead

        var regex = /\s+/gi;
        var wordCount = value.trim().replace(regex, ' ').split(' ').length - 1;
         // length - 1 is more accurate because 'cat dog'.split().length == 2, but theres only one space!

        $('#text1').html(wordCount);
      </script>
    </head>

    <body id="background">
      <div id="textBlock">
        <div id="wrapper">
          <p id="text1">This is test text in this template</p>
        </div>
      </div>
    </body>

    </html>

1 个答案:

答案 0 :(得分:0)

假设:

<p id="text1">This is test text in this template</p>

以下代码似乎可以解决问题。输出为7。

var value = $('#text1').text();
var regex = /\s+/gi;
var wordCount = value.trim().split(regex).length;
$('#text1').html(wordCount);

jsfiddle