站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Javascript 专题在Javascript中为String对象添加trim,ltrim,rtrim方法

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

摘要: 在Javascript中为String对象添加trim,ltrim,rtrim方法
<textarea readonly style="border:none;font-family:Courier New;line-height:150%;width:760px;overflow-y:visible">


利用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, "");
}
怎么样,简单吧,下面看一个使用的实例:
&lt;script language=javascript&gt;
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 + ")");

&lt;/script&gt;

</td> </tr> </table></td> </tr>   
</td> </tr> </table> </textarea>
↑返回目录
前一篇: JavaScript实例 实现聊天室在线人员无刷新
后一篇: JavaScript实例 站内搜索例子 (二)