How to count words in JavaScript using JQuery

前端 未结 7 1130
旧巷少年郎
旧巷少年郎 2020-12-09 13:17

I have a simple html text box. When I \"submit\" the form that the text box is in, I would like to get a variable with the number of words inside using Jqu

相关标签:
7条回答
  • 2020-12-09 13:42

    Try this to count words in JavaScript using JQuery.

    $(document).ready(function(){
        $("button").click(function(){
            var words = $.trim($("#name").val()).split(" ");
            alert(words.length);
        });
    });
    

    See more @ Count words in JavaScript using JQuery

    0 讨论(0)
  • A slight improvement on other answers as is deals with more edge cases. ie using multiple spaces and punctuation together and also handles punctuation at the start and end of text properly.

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

    It first strips off any punctuation and spaces at the beginning and end of the text and then counts what's left. Obviously one can add more punctuation (like exclamation marks) if required.

    0 讨论(0)
  • 2020-12-09 13:51
    var str = $('#name').val(),
        count = str.split(' ').length;
    

    Assuming that each word is seperated by a space

    0 讨论(0)
  • 2020-12-09 13:52

    You would split the string and then count the length of the resulting array.

    $('input[type="submit"]').click( function() {
        var words = $('#name').val().split(' ');
        alert(words.length);
    });
    
    0 讨论(0)
  • 2020-12-09 13:52

    You can specify multiple characters to split your source string :

    $('input[type="submit"]').click( function() {
        var words = $('#name').val().split(/[\s\.,;]+/);
        console.log(words.length);
    });
    
    0 讨论(0)
  • 2020-12-09 13:58

    Using the regular expression below allow us to remove any kind of white space (single or multiples) so that the count is very accurate.

    $('#name').keyup(function(){
       var wordCount = $(this).val().split(/[\s\.\?]+/).length;
       console.log(wordCount);
    });
    

    See this jQuery plugin I have developed:

    https://github.com/mcdesignpro/maxLenght

    0 讨论(0)
提交回复
热议问题