A slight improvement over other answers, as we are talking about a larger number of cases. those. Use multiple spaces and punctuation together, and correctly handle punctuation at the beginning and end of the text.
var numOfWords = $('#name').val().replace(/^[\s,.;]+/, "").replace(/[\s,.;]+$/, "").split(/[\s,.;]+/).length;
First, he discards any punctuation and spaces at the beginning and end of the text, and then counts what remains. Obviously, if necessary, you can add more punctuation marks (for example, exclamation points).
source share