0

i am trying to make a simple trim function but this doesnt works. any help pls?

function tr(input){
            var i;
            var str;
            for(i=0; i<input.length-1; i++){
            if(text.charAt(i)==" "){
                    str+=""+text.charAt(i)
                    
            }
           return str
        }
        }
2
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by hielo
0

yes i know that there is a reqular expression for this but i dont want it in that way. thx anw

0

OK, then use a variable (stop) to iterate the string from right to left. Stop once you find a non-space.

Repeat the above, but iterating from left to right.

then use the substring() method to return the trimmed string.

0

you should also check for newlines and carriage returns:

function tr(input)
{
	var start=-1, end=input.length;
	while( --end>start && (input.charAt(end)==" " || input.charAt(end)=="\n" || input.charAt(end)=="\r") ){}
	++end;
	while( ++start<end && (input.charAt(start)==" " || input.charAt(start)=="\n" || input.charAt(start)=="\r")){}
	
return input.substring(start,end);
}

Edited by hielo: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.