Search code examples
javascriptjqueryword-count

Word count on element jQuery


I am trying to get the word count from 1 element and put it onto a variable. But i am not sure the best way to do this. Any ideas?

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>

I have tried answers in this Question, added the below code and got this error. TypeError: undefined is not an object (evaluating '$('#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>


Solution

  • Given:

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

    The following code seems to do the trick. The output is 7.

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

    jsfiddle