Useer
Useer

Reputation: 61

Regex for javascript to count words (excluding numbers)

I have this function

String.prototype.countWords = function(){
    return this.split(/\s+\b/).length;
}

which counts words in textarea, but it also counts numbers inserted, I was wondering how to count words but not numbers, so ignoring the numbers,

Upvotes: 3

Views: 674

Answers (2)

karthik manchala
karthik manchala

Reputation: 13650

Your regex counts the number of spaces.. Use the following for words (without numbers):

/[a-zA-Z]+/

For splitting use the following:

this.split(/[\s\D]+/).length

Upvotes: 1

Jo Oko
Jo Oko

Reputation: 358

The following regex might help you out:

String.prototype.countWords = function(){
    return this.split(/\s+[^0-9]/).length;
}

The ^ negates the characters in the brackets, so all characters are allowed to follow the whitespaces except any numbers.

By the way: here is a good place to test your regex: http://regexpal.com/

Upvotes: 1

Related Questions