当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 在Javascript中为String对象添加trim,ltrim,rtrim方法

Javascript
JavaScript教程:浏览器对象层次及其主要作用
JavaScript教程:文档对象功能及其作用
JavaScript教程:JS对象系统的使用范例
JavaScript教程:窗口及输入输出
JavaScript教程:简单的输入、输出例子
JavaScript教程:JS窗口及输入输出范例
JavaScript教程:JavaScript窗体基础知识
JavaScript教程:JS窗体中的基本元素
JavaScript教程:用JS脚本实现Web页面信息交互范例
JavaScript教程:什么是框架?
JavaScript教程:如何访问框架?
JavaScript教程:用JS实现更复杂的交互范例
JavaScript静态页面值传递:URL篇
JavaScript静态页面值传递:Window.open篇
JavaScript静态页面值传递:Cookie篇
JavaScript中sort排序函数
JavaScript中splice数组函数
JavaScript中split字符串函数
JavaScript中small对象函数
JavaScript:世界上误解最深的语言

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-10   浏览: 400 ::
收藏到网摘: n/a

 

 

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