做註冊、表單驗證時,用戶很可能不小心輸入多餘的空格,這時就需要把字符串首尾的空格去掉。下面整理了五種常見的 JS 實現,並給出效率上的對比。
復制代碼 代碼如下:
// 供使用者調用
function trim(s){
return trimRight(trimLeft(s));
}
// 去掉左邊的空白
function trimLeft(s){
if(s == null) {
return "";
}
var whitespace = new String(" \t\n\r");
var str = new String(s);
if (whitespace.indexOf(str.charAt(0)) != -1) {
var j=0, i = str.length;
while (j < i && whitespace.indexOf(str.charAt(j)) != -1){
j++;
}
str = str.substring(j, i);
}
return str;
}
// 去掉右邊的空白
function trimRight(s){
if(s == null) return "";
var whitespace = new String(" \t\n\r");
var str = new String(s);
if (whitespace.indexOf(str.charAt(str.length-1)) != -1){
var i = str.length - 1;
while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){
i--;
}
str = str.substring(0, i+1);
}
return str;
}
復制代碼 代碼如下:
<SCRIPT LANGUAGE="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>
復制代碼 代碼如下:
$.trim(str)
jQuery 內部實現為:
復制代碼 代碼如下:
function trim(str){
return str.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');
}
復制代碼 代碼如下:
function trim(str){
return str.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g, '');
}
復制代碼 代碼如下:
function trim(str){
str = str.replace(/^(\s|\u00A0)+/,'');
for(var i=str.length-1; i>=0; i--){
if(/\S/.test(str.charAt(i))){
str = str.substring(0, i+1);
break;
}
}
return str;
}
經過測試,第五種方法在處理長字符串時效率最高。
復制代碼 代碼如下:
<script type="text/JavaScript">
// 去掉空格
function SystemTrim(str) {
var regExp = /(^\s*)|(\s*$)/;
return str.replace(regExp,"");
}
// 調用
function add()
{
var ownername=document.form1.ownername.value;
if(SystemTrim(ownername)=="")
{
alert("請輸入您的稱呼!");
return;
}
}
</script>
實踐中,如果追求簡潔可直接用正則或 $.trim;若面對大量長文本處理,第五種「先裁左側再反向掃描右側」的寫法在性能上更有優勢。