Click to See Complete Forum and Search --> : Removing the white spaces


bharadwajrv
September 21st, 2002, 04:15 AM
Hi,
how to remove the white spaces before and after a text in the text box control using java script.
thanks in adv,. Venu

websmith99
September 23rd, 2002, 01:56 PM
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".

Zvona
September 24th, 2002, 06:06 AM
Article of a function meant for trimming whitespaces from string:
http://www24.brinkster.com/zvona/zTrim.html

websmith99
September 24th, 2002, 10:24 AM
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.