背景:
阅读内容

String添加trim,ltrim,rtrim

[日期:2006-10-10]   [字体: ]
利用Javascript中每个对象(Object)的prototype属性我们可以为Javascript中的内置对象添加我们自己的方法和属性。

  以下我们就用这个属性来为String对象添加三个方法:Trim,LTrim,RTrim(作用和VbScript中的同名函数一样)

String.prototype.Trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.LTrim = function()
{
return this.replace(/(^\s*)/g, "");
}
String.prototype.Rtrim = function()
{
return this.replace(/(\s*$)/g, "");
}
  怎么样,简单吧,下面看一个使用的实例:

$#@60;script language=javascript$#@62;
String.prototype.Trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
} 
 
var s = " leading and trailing spaces "; 
 
window.alert(s + " (" + s.length + ")"); 
 
s = s.Trim(); 
 
window.alert(s + " (" + s.length + ")"); 
 
$#@60;/script$#@62;    
收藏 推荐 复制 打印 | 录入:admin | 阅读:
版权所有 Copyright© 2006-2008 黑马网上创业指南 联系方式:heima123#gmail.com