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
        }
        }
function tr(str)
{
return String(str).replace(/(^\s+|\s+$)/g,'');
}

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

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.

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);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.