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?
" Robert Neil Cook "
3 //"Robert Neil Cook"
var str = $.trim( $('#inval').val() );
var Fstr = str.split(' ').length;
You can use
var str = " Robert Neil Cook "; var len = str.match(/\S+/g).length; console.log(len);
.match(/\S+/g) would return you the words without any space as an array and you can use
length property of it.