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

2019-12-27,,,,,,

以下我们就用这个属性来为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 language=javascript>
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 + ")");
</script>

您可能感兴趣的文章:

  • JavaScript原生对象之String对象的属性和方法详解
  • 浅谈JavaScript中的String对象常用方法
  • javascript中String对象的slice()方法分析
  • 为Javascript中的String对象添加去除左右空格的方法(示例代码)
  • js String对象中常用方法小结(字符串操作)
  • Javascript String对象扩展HTML编码和解码的方法
  • JavaScript中String对象的方法介绍

《在Javascript中为String对象添加trim,ltrim,rtrim方法.doc》

下载本文的Word格式文档,以方便收藏与打印。