CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2001
    Location
    UK
    Posts
    308

    Removing the white spaces

    Hi,
    how to remove the white spaces before and after a text in the text box control using java script.
    thanks in adv,. Venu
    Venu Bharadwaj
    "Dream it. U can do it!"

  2. #2
    Join Date
    Aug 2002
    Location
    Reykjavik, Iceland
    Posts
    201
    Since JavaScript doesn't have a trim() method like Java, you can do this:

    - loop through the characters of the string starting from the beginning. when you find the first non-space character, note it's position in the string (the starting index)

    - loop through again, starting from the ending and going backwards. when you find the first non-space character note the position in the string (the ending index)

    - loop through the string again from the new starting and ending index and construct the new, trimmed string.

    mystring = " foobar ";
    trimedString = "";
    for (i=0; i<mystring.length; i++) {
    if (mystring.charAt(i) != " ") {
    startIndex = i;
    break;
    }
    }
    for (i=(mystring.length-1); i>0; i--) {
    if (mystring.charAt(i) != " ") {
    endIndex = i;
    break;
    }
    }
    for (i=startIndex; i<=endIndex; i++) {
    trimedString += mystring.charAt(i);
    }
    </script>


    trimedString will have a value of "foobar".

  3. #3
    Join Date
    Jan 2002
    Location
    Helsinki, Finland
    Posts
    99
    Article of a function meant for trimming whitespaces from string:
    http://www24.brinkster.com/zvona/zTrim.html
    Zvona - First aid for client-side web design

  4. #4
    Join Date
    Aug 2002
    Location
    Reykjavik, Iceland
    Posts
    201
    Good work Zvona.

    I was going to use JavaScript regular expressions
    as well, but decided to post a solution that
    would work on the most browsers possible.

    Note that your solution requires the user to
    have a browser that supports JavaScript 1.2 -
    if the userbase is guaranteed to use 4th
    generation browsers and newer (IE4+, NN4+)
    then regular expressions are a more elegant
    way to go.

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured