javascript 去空格函数实现代码

HTML 内容:

 <table style="margin-top: 100px;border-top:black;">
            <tr><td>用户名:</td><td><input type="text" id="txtusername" name="txtusername"/></td></tr>
            <tr><td>&nbsp;&nbsp;码:</td><td><input type="text" id="txtpassword" name="txtpassword"/></td></tr>
            <tr><td colspan="2" align="center"><input type="button" id="btnSubmit" name="btnSubmit" value="登录" onclick="FromSubmit();"/></td></tr>
        </table>

脚本内容(String的属性):

<script type="text/javascript">
        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> 

应用:

<script type="text/javascript">
        function FromSubmit() {
            var username = document.getElementById("txtusername").value;
            var password = document.getElementById("txtpassword").value;
            if(username.trim()!="" && username.trim()=="admin" && password.trim()!="" && password.trim()=="admin" ) {
                document.getElementById("form1").submit();
            }        
        }
    </script>

将trim写成函数形式:

<script type="text/javascript"> 
function trim(str){ //删除左右两端的空格 
return str.replace(/(^\s*)|(\s*$)/g, ""); 
} 
function ltrim(str){ //删除左边的空格 
return str.replace(/(^\s*)/g,""); 
} 
function rtrim(str){ //删除右边的空格 
return str.replace(/(\s*$)/g,""); 
} 
</script>

 

posted @ 2013-04-07 10:07  王然8911  阅读(166)  评论(0编辑  收藏  举报