您的位置:首页 > Web前端 > JavaScript

在Javascript中为String对象添加trim,ltrim,rtrim方法

2005-01-14 15:11 781 查看
利用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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: