user1871516
user1871516

Reputation: 1009

Check a string contain how many word in javascript

I would like to check how many words in a string

eg.

 asdsd sdsds sdds 

3 words

The problem is , if there is more than one space between two substring , the result is not correct

here is my program

function trim(s) {   
  return s.replace(/^\s*|\s*$/g,"")   
} 

var str = trim(x[0].value);
var parts = str .split(" ");
alert (parts.length);

How to fix the problem? thanks for help

Upvotes: 2

Views: 2687

Answers (6)

NeverHopeless
NeverHopeless

Reputation: 11233

An even shorter pattern, try something like this:

(\S+)

and the number of matches return by regex engine would be your desired result.

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

try:

function trim(s) {   
  return s.replace(/^\s*|\s*$/g,"")   
} 
var regex = /\s+/gi;
var value = "this ss ";
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
console.log( wordCount );

Upvotes: 0

Kuldeep Raj
Kuldeep Raj

Reputation: 795

Please use this one Its already used by me in my project :

function countWords(){
    s = document.getElementById("inputString").value;
    s = s.replace(/(^\s*)|(\s*$)/gi,"");
    s = s.replace(/[ ]{2,}/gi," ");
    s = s.replace(/\n /,"\n");
    document.getElementById("wordcount").value = s.split(' ').length;
}

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

You could just use match with word boundaries:

var words = str.match(/\b\w+\b/g);

http://jsbin.com/abeluf/1/edit

Upvotes: 3

Amit Sharma
Amit Sharma

Reputation: 1210

var parts = str .split(" ");
parts = parts.filter(function(elem, pos, self) {
     return elem !== "";
});

Please try this. Make sure you are using latest browser to use this code.

Upvotes: 2

user2538908
user2538908

Reputation:

It's easy to find out by using split method, but you need to sort out if there are any special characters. If you don't have an special characters in your string, then last line is enough to work.

s = document.getElementById("inputString").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
document.getElementById("wordcount").value = s.split(' ').length;

Upvotes: 1

Related Questions