欢迎光临
我们一直在努力

在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)