Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: Trim spaces

  1. #1
    Regular Coder
    Join Date
    Jul 2002
    Posts
    362
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Trim spaces

    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:
    Code:
          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.

    /^\s+|\s+$/g,""

  • #2
    Smokes a Lot
    Join Date
    Jul 2003
    Location
    CA, USA
    Posts
    1,594
    Thanks
    5
    Thanked 20 Times in 20 Posts
    Try:

    Code:
    function noWhiteSpace(str){
                    var re=/\s/g;
                    var fix_str=str.replace(re,"");
                    return fix_str;
                }
    Basscyst
    Helping to build a bigger box. - Adam Matthews

  • #3
    Regular Coder
    Join Date
    Mar 2006
    Posts
    728
    Thanks
    35
    Thanked 132 Times in 123 Posts
    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):

    Code:
    String.prototype.clean=function(){
    	var str= this.replace(/(^\s+)|(\s+$)/g,'');
    	return str.replace(/ {2,}/g,' ');
    }
    Last edited by mrhoo; 06-25-2008 at 02:40 AM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •