打印本文 打印本文 关闭窗口 关闭窗口
去掉字符串前后的空格
作者:武汉SEO闵涛  文章来源:敏韬网  点击数877  更新时间:2009/4/23 11:23:16  文章录入:mintao  责任编辑:mintao

//为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>

打印本文 打印本文 关闭窗口 关闭窗口