View Full Version : Trim spaces

06-25-2008, 12:49 AM
I want to make sure at least 3 characters are entered into a search field.
For example I dont want this to go by where it has spaces in beginning and space between 2 characters:
a b

Is there a regular expression or someway to trim the spaces between the characters so I dont let less than 2 characters get submitted?

Here is one reg expression I tried but it let spaces between characters get entered so less than 3 characters were submitted.


06-25-2008, 01:04 AM

function noWhiteSpace(str){
var re=/\s/g;
var fix_str=str.replace(re,"");
return fix_str;


06-25-2008, 02:34 AM
You can count the number of characters in a string that are not whitespace-

var count=str.match(/(\S)/g).length;

I would go for letters and numbers for the count-

var count=str.match(/(\w)/g).length;

It is handy to trim leading and trailing whitespace from user input-
this one trims outside whitespace and reduces multiple space characters in the text to single spaces.
(It leaves interior line breaks and tabs alone):

var str= this.replace(/(^\s+)|(\s+$)/g,'');
return str.replace(/ {2,}/g,' ');