Jump to content

how to count actual words in a form field, not just the spaces


jasonc

Recommended Posts

i have taken this code and see that it is possible to fool the script in to thinking that more than one word was typed by entering many spaces.  How do I count actual words, or thinking about it how to i trim the spaces from the start and end of the string before it is checked ?

 

http://www.mediacollege.com/internet/javascript/text/count-words.html

 

 

if (document.getElementsByName('fullname')[0].value.split(' ').length < 2) {
	// do something
	}

It's been a while, but something like this... It also handles extra white space between words too!

String.prototype.trim = function () {
    //return this.replace(/^\s*/, "").replace(/\s*$/, "");
    return this.replace(/^\s+|\s+$/g, '') ;
}

var ss = "   I told   you it'd   be   alright!   ".trim().replace(/\s+/g,' ');
alert("ss: " + ss);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.