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

来源:互联网 发布:淘宝服装免费代理商 编辑:程序博客网 时间:2024/05/21 18:34
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

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

<<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击