How to count words in JavaScript using JQuery

半世苍凉 提交于 2019-11-27 02:55:34

问题


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 Jquery. I would also like to check if the inputted text is only letters, numbers and hyphens (also in jquery). I do not need to count the words as the user types, just when the form is submitted. The form won't submit if jquery is turned off so I guess there are no security risks by not using php. Is this true?

HTML:

<input type='text' name='name' id='name' />
<input type='button' value='Sign Up' id='signUp'>

JQUERY (attempt):

var wordcount = $('#name').val()  // i don't know how to count the words 

回答1:


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);
});



回答2:


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.




回答3:


Is very useful to remove whitespaces from the beginning and end of the string usign $.trim(). You can use keyup event for a realtime counting.

$('#name').keyup(function(){
    var words = $.trim($(this).val()).split(' ');
    console.log(words.length);
});



回答4:


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);
});



回答5:


var str = $('#name').val(),
    count = str.split(' ').length;

Assuming that each word is seperated by a space




回答6:


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




回答7:


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



来源:https://stackoverflow.com/questions/8752853/how-to-count-words-in-javascript-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!