为什么不是'我的修剪功能不起作用

Why isn't my trim function working?

本文关键字:修剪 功能 不起作用 我的 为什么不      更新时间:2023-09-26

我应该为我的javascript类创建一个trim函数。我以为我什么都做对了,但由于某种原因,它不起作用。有人能检查我的代码,看看我缺少了什么,或者如何使其工作吗?

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;
}

您应该使用's来匹配空白。我还为您简化了函数。

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();
}

:-)