Becky Becky - 4 months ago 14
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?

E.g.
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;
console.log(fstr);

Jai Jai
Answer

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

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

console.log(len);

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