js去掉字符串前后空格的五種方法


轉載 :http://www.2cto.com/kf/201204/125943.html

第一種:循環檢查替換
[javascript]
//供使用者調用  
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;  
}  
//去掉右邊的空白 www.2cto.com   
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;  

第二種:正則替換
[javascript]
<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
[javascript]
$.trim(str) 
jquery內部實現為:
[javascript]
function trim(str){   
    return str.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');   
}   
第四種:使用motools
[javascript]
function trim(str){   
    return str.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g, '');   
}  
第五種:裁剪字符串方式
[javascript]
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">

var str= ' 我你的';

alert(trim(str));

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>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM