By Ben
方法一:
function KillSpace(x){
while((x.length>0) && (x.charAt(0)==' '))
x = x.substring(1,x.length);
//while((x.length>0) && (x.charAt(x.length-1)==' '))
while(x.length>0)
x = x.substring(0,x.length-1);
alert("Kill=" + x + "==")
return x;
}
实例: var a = KillSpace(“ abc “); //得出a == “abc“
方法二:
String.prototype.trim = function()
{
return this.replace(/(^\s+)|\s+$/g,"");
}
实例: var a = “ abc “.trim(); //得出a == “abc“
JavaScript去除字符串首尾空格的方法
博客介绍了JavaScript中去除字符串首尾空格的两种方法。方法一是自定义函数KillSpace,通过循环和字符串截取实现;方法二则是利用原型链,在String对象上添加trim方法,使用正则表达式替换空格。并给出了相应的实例。
1049

被折叠的 条评论
为什么被折叠?



