Becky Becky - 8 months ago 35
jQuery Question

Count words input field

Basically I need to get the number of words in an input field. So the approach is to trim the leading and trailing spaces and also to limit the remaining spaces within the string to 1. So that I'll be able to get the number of words. How do I do this?

input value:

" Robert Neil Cook "

Expected output:

3 //"Robert Neil Cook"

This is what I tried.

var str = $.trim( $('#inval').val() );
var Fstr = str.split(' ').length;

Jai Jai

You can use .match(/\S+/g):

var str = "   Robert   Neil       Cook   ";
var len = str.match(/\S+/g).length;


This .match(/\S+/g) would return you the words without any space as an array and you can use length property of it.