以下我们就用这个属性来为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, "");
}
怎么样,简单吧,下面看一个使用的实例:
<script> <BR>String.prototype.Trim = function() <BR>{ <BR> return this.replace(/(^\s*)|(\s*$)/g, ""); <BR>} <BR>var s = " leading and trailing spaces "; <BR>window.alert(s + " (" + s.length + ")"); <BR>s = s.Trim(); <BR>window.alert(s + " (" + s.length + ")"); <BR></script>