欢迎光临
我们一直在努力

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

建站超值云服务器,限时71元/月

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

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 在Javascript中为String对象添加trim,ltrim,rtrim方法
分享到: 更多 (0)

相关推荐

  • 暂无文章