好看的挠脚心的电视剧:Javascript 中怎么去掉空格与NULL值

来源:百度文库 编辑:神马品牌网 时间:2024/04/28 00:35:56
<input type="text" name="user" >我想做的是,当输入的只有空格时,表示什么也没有输入,当输入的字符串中有空格的时候把空格去掉。
简单点的方法有吗。正则这些就表来了哈,多谢

简单的方法?Javascrpit里面可没有什么replace和trim方法,这样吧~自己写一个吧:
<script language=Javascript> //自己动手为string添加Trim
function String.prototype.Trim() {return this.replace(/(^\s*)|(\s*$)/g,"");}
function String.prototype.Ltrim(){return this.replace(/(^\s*)/g, "");}
function String.prototype.Rtrim(){return this.replace(/(\s*$)/g, "");}
var str = " aaa ";
alert(str.Trim());
</script>

或者参照
http://www.2solo.net/blog/showlog.asp?log_id=446&cat_id=0

-----------------------------

str.replace(/\-/g,"!")则可以替换掉全部匹配的字符(g为全局标志)。

试试user.replace(/\ /g,"")

replace()
The replace() method returns the string that results when you replace text matching its first argument
(a regular expression) with the text of the second argument (a string).
If the g (global) flag is not set in the regular expression declaration, this method replaces only the first
occurrence of the pattern. For example,

var s = "Hello. Regexps are fun.";s = s.replace(/\./, "!"); // replace first period with an exclamation pointalert(s);

produces the string “Hello! Regexps are fun.” Including the g flag will cause the interpreter to
perform a global replace, finding and replacing every matching substring. For example,

var s = "Hello. Regexps are fun.";s = s.replace(/\./g, "!"); // replace all periods with exclamation pointsalert(s);

yields this result: “Hello! Regexps are fun!”