使用正则表达式分别匹配首、尾空格,替换成空字符串: var $memberNum = $("#txtMemberNum").val().replace(/^\s*/g,"").replace(/\s*$/g,"");