DIV CSS 佈局教程網

JS 去除字符串前後空格的 5 種實現方式對比
編輯:關於JavaScript     

做註冊、表單驗證時,用戶很可能不小心輸入多餘的空格,這時就需要把字符串首尾的空格去掉。下面整理了五種常見的 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>

第三種:使用 jQuery

復制代碼 代碼如下:

$.trim(str)

jQuery 內部實現為:

復制代碼 代碼如下:

function trim(str){
    return str.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');
}

第四種:使用 MooTools

復制代碼 代碼如下:

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;若面對大量長文本處理,第五種「先裁左側再反向掃描右側」的寫法在性能上更有優勢。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved