1. 程式人生 > >jquery $.trim()去除字串空格

jquery $.trim()去除字串空格

JQuery刪除字串的前後空格很簡單,使用$.trim(StringText);//StringText是要刪除空格的字串

$.trim(str)

返回:string;

說明:去掉字串首尾空格。

示例:

 
先看個錯誤程式碼錯誤程式碼:

 程式碼如下 複製程式碼
<input type="text" name="" id="results" value=""/>
var content = $('#content').val(); 
if(content.trim() == '') 
alert('空'); 

上面的寫法在firefox下不會報錯,但在ie下確會報錯

所以要寫成下面格式:

 程式碼如下 複製程式碼

<input type="text" name="" id="results" value=""/>

var content = $('#results').val(); 
if($.trim(content) == '') 
alert('空');

或者

var content = $('#content').val();

if(jQuery.trim(content) == '')

alert('空');

一個例項

 程式碼如下 複製程式碼

<!doctype html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <button>show trim example</button>
<script>

$("button").click(function () {
var str = "     lots of spaces before and after     ";
alert("'" + str + "'");

str = jquery.trim(str);
alert("'" + str + "' - no longer");
});

</script>

</body>
</html>