利用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, "");
}
怎么样,简单吧,下面看一个使用的实例:
<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>
 
 

相关文章:

  • 2021-08-01
  • 2022-12-23
  • 2022-12-23
  • 2021-05-24
猜你喜欢
  • 2022-12-23
  • 2022-03-09
  • 2022-12-23
  • 2021-12-23
  • 2022-01-19
  • 2021-09-13
相关资源
相似解决方案