日期:2014-05-16  浏览次数:20354 次

JSP/JS 正则表达式和函数两种方式实现 Trim 函数
利用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, "");
}


/******************************

***   此方法同上面的Trim()  ***

function  trim(str)
{
    for(var  i  =  0 ; i<str.length && str.charAt(i)==" "; i++ ) ;
    for(var  j  = str.length; j>0 &&  str.charAt(j-1)==" " ; j--) ;
    if(i>j)  return  "";
    return  str.substring(i,j);
}

******************************/
下面看一个使用的实例:
<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>


说明:
^ 匹配输入字符串的开始位置,除非在方括号表达式中使用,此时它表示不接受该字符集合。要匹配 ^ 字符本身,请使用 \^。

\s 与任何白字符匹配,包括空格、制表符、分页符等。等价于"[ \f\n\r\t\v]"。

$ 匹配输入的结尾。

* 匹配前一个字符零次或几次。例如,"zo*"可以匹配"z"、"zoo"。

/g 好像是全局匹配吧