JavaScript如何自定义trim方法
相比vbscript,javascript在字符串处理方面已经很强大了,但是偏偏缺少去除字符串前后空格的trim方法。
//cleartherightandleftspace
functiontrim(s){
returntrimRight(trimLeft(s));
}
//cleartheleftspace
functiontrimLeft(s){
if(s==null){
return"";
}
varwhitespace=newString("\t\n\r");
varstr=newString(s);
if(whitespace.indexOf(str.charAt(0))!=-1){
varj=0,i=str.length;
while(j<i&&whitespace.indexOf(str.charAt(j))!=-1){
j++;
}
str=str.substring(j,i);
}
returnstr;
}
//cleartherightspace
functiontrimRight(s){
if(s==null)return"";
varwhitespace=newString("\t\n\r");
varstr=newString(s);
if(whitespace.indexOf(str.charAt(str.length-1))!=-1){
vari=str.length-1;
while(i>=0&&whitespace.indexOf(str.charAt(i))!=-1){
i--;
}
str=str.substring(0,i+1);
}
returnstr;
}
以上就是本文的全部内容,希望对大家的学习有所帮助。
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语