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

利用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>

版权声明:
作者:Kiyo
链接:https://www.wkiyo.cn/html/2008-01/i288.html
来源:Kiyo's space
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>