Atul Verma
Atul Verma

Reputation: 381

How to count the words and numbers in textarea using regular expression?

I have problem on regular expression, its like i am trying to count the number of word in text area but i am not getting desired output. The main problem is, that it does not count the numbers for example "Hello world 123" it counts only 2. and for "123" it does not count at all. my regular expression isresponse.trim().replace(/\b[\s,-:;'"_]*\b/gi, ' ').split(' ');

Upvotes: 0

Views: 360

Answers (5)

aorcsik
aorcsik

Reputation: 15552

Your solution is almost perfect, but there are two problems:

  1. replace "at least one" occurrence of word separator characters (+) instead of any (*)
  2. you have a ,-; character range in your character class ([...]), which unfortunately include all numbers. When you want to match - (dash) put it always at the beginning of the character class!

So the corrected regular expression: /\b[-\s,:;'"_]+\b/gi

Edit: If you need to match every non-alphanumeric character, the use [\W_]

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

You should use /\b|\d+/gi to search for word boundaries or numbers, then count the number of elements in the array.

var array = response.trim().match(/\b|\d+/gi);
var count = array.length;

Upvotes: 1

Michael
Michael

Reputation: 12806

As you've tagged this with php I assume a PHP answer is acceptable, in which case you don't need a regular expression. You can just use str_word_count:

echo str_word_count("Hello world 123!", 0, '0..9'); // 3

Notice the third parameter which allows you to specify additional characters which make up a word. As a default, numbers are not included, hence the addition here.

Alternatively you can use preg_match_all:

preg_match_all('/\b[a-z\d]+\b/i', $string);

This will only count letters and numbers as word-characters.

Upvotes: 0

Robin
Robin

Reputation: 9644

You can use

array = response.trim().match(/\w+/g);
count = array.length;

In your array only the words (alphanumerical strings) will be stored.

For the record, \w is short for [a-zA-Z0-9], which means it won't catch correctly words with special characters, like journée, but it will return 6 for I'd like 1 cup...plz!.

Upvotes: 0

Sujith PS
Sujith PS

Reputation: 4864

Take a look at this demo.

DEMO

You can use : response.replace(/['?:_!'"@#$&%\^*()\\\/.-]/g,"").split(/[ \n\r]/);

Upvotes: 0

Related Questions