I'm supposed to create a trim function for my javascript class. I thought I had everything right, but for some reason it won't work. Can someone check my code to see what I'm missing or how to make it work?
window.onload=function()
{
window.alert(trim(" test"));
};
function trim(data)
{
var result;
var whitespace;
var start;
whitespace="\n\r\t\f";
start=0;
if(typeof data === "string")
{
while(start<data.length, data.charAt(start)===whitespace)
{
start=start+1;
} //end loop scope
var end;
end=data.length-1;
while(end>=0, data.charAt(end)===whitespace)
{
end=end-1;
} //end loop scope
if(end<start)
{
result="";
}
else
{
result=data.substring(start, end+1);
}
}
else //else for first if statement
{
return result;
}
return result;
}
You should use \\s
to match whitespace. I've also simplified the function for you.
function trim(data) { if(typeof data === "string") { return data.replace(/(^[\\s\\r\\n\\t\\f]+|[\\s\\r\\n\\t\\f]+$)/g, ''); } return data; } var result = trim(' test '); document.write(result); document.write('<br>Length of string: '+result.length);
function trim(string)
{
return string.trim();
}
:-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.