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

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 ghj1976 的 blog

 

 

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

 

本文关键:在Javascript中为String对象添加trim,ltrim,rtrim方法
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top