[英]Why isn't my trim function working?
I'm supposed to create a trim function for my javascript class. 我应该为我的javascript类创建一个trim函数。 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. 您应该使用
\\s
来匹配空格。 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();
}
:-) :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.