元素 jQuery 的字数统计

Word count on element jQuery

我正在尝试从 1 个元素中获取字数并将其放入一个变量中。但我不确定这样做的最佳方法。有什么想法吗?

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 is not an object (评估 '$('#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>

鉴于:

<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