Becky
Becky

Reputation: 5585

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. Below is my code to 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);

Upvotes: 2

Views: 1211

Answers (7)

Jai
Jai

Reputation: 74738

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

var str = "   Robert   Neil       Cook   ";
var arr = str.match(/\S+/g);
var newstr = arr.join() 
console.log('length::::>', arr.length);
console.log('newstr::::>', newstr);

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

Upvotes: 1

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5039

Try below :

str= "   Robert   Neil       Cook   " ;
str = $.trim(str.replace(/ +(?= )/g,'')); // replace multiple spaces to single space
console.log(str)
var words = str.split(' '); // count the no of words using .split() method
alert(words.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Upvotes: 2

Ronak Patel
Ronak Patel

Reputation: 3444

Very simple solution, try this

var str = "   Robert   Neil       Cook   ";
str = str.trim();
var str = str.split('  ').join('');
var fstr = str.split(' ').length;
console.log(fstr);

Upvotes: 0

Divyesh Patoriya
Divyesh Patoriya

Reputation: 518

Please have a look attached snippet.

var str = $.trim( $('#inval').val() );
str1 = str.replace(/ +(?= )/g,'')
var fstr = str1.split(' ').length;
console.log(fstr);
console.log(str1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="  Robert   Neil       Cook   "  id="inval">

Upvotes: 0

Harry Bomrah
Harry Bomrah

Reputation: 1668

You can Haresh Vidja's function more compact like this

function countWords(s){
  return s.trim().replace(/[ ]{2,}/gi," ").split(" ").length;
}

console.log(countWords("some words here")

Upvotes: 0

Karthikeyan
Karthikeyan

Reputation: 347

Try this code..

var str = $.trim( $('#inval').val() );
var words = str.split(' ').filter(v=>v!='').length;

Upvotes: 0

Haresh Vidja
Haresh Vidja

Reputation: 8496

You can use below custom function for count words

    function countWords(s){
        s = s.replace(/(^\s*)|(\s*$)/gi,"");//exclude  start and end white-space
        s = s.replace(/[ ]{2,}/gi," ");//2 or more space to 1
        s = s.replace(/\n /,"\n"); // exclude newline with a start spacing
        return s.split(' ').length; 
    }

    alert(countWords("How are you?"));

Upvotes: 2

Related Questions