Rolinson's Blog

ASP.NET , J2ME , WAP
(还有收藏网络上的技术文章,以便一急之用)

博客园 首页 新随笔 联系 订阅 管理

利用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, "");
}



Sample 简单例子:
<script>
    String.prototype.Trim = function()
    {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    }

    var s = " leading and trailing spaces  "

    s = s.Trim();

    window.alert( "_" + s + "_" );

</script>

posted on 2005-01-14 15:11  ByNow  阅读(389)  评论(0编辑  收藏  举报