正 文

去掉字符串前后的空格


www.7dspace.com  更新日期:2005-8-16 5:49:46  七度空间


//为String对象原型添加trim方法,去掉字符串前后的空格
String.prototype.trim = function()
{
    // 用正则表达式将前后空格,用空字符串替代。
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

//------------------------------------------------------------------------------------------------------

例子:

<script>
String.prototype.trim = function()
{
    // 用正则表达式将前后空格,用空字符串替代。
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

// 有空格的字符串
var s = "    leading and trailing spaces    ";

// 显示 "    leading and trailing spaces     (35)"
window.alert(s + " (" + s.length + ")");

// 删除前后空格
s = s.trim();
// 显示"leading and trailing spaces (27)"
window.alert(s + " (" + s.length + ")");

</script>


上一篇:表格中两行的颜色交替显示
下一篇:JavaScript实际应用:子窗口和父窗口交互
作者:  来源: ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐