js去掉字符串前后空格的五種方法
第一種:循環檢查替換
//供使用者調用function trim(s){return trimRight(trimLeft(s));}//去掉左邊的空白function trimLeft(s){if(s == null) {return '';}var whitespace = new String(' tnr');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(' tnr');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;}
第二種:正則替換
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, '');}
第三種:使用jquery
$.trim(str)jquery內部實現為:[javascript]function trim(str){return str.replace(/^(s|u00A0)+/,’’).replace(/(s|u00A0)+$/,’’);}
第四種:使用motools
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;}
轉自:http://www.2cto.com/kf/201204/125943.html
相關文章:
1. React+umi+typeScript創建項目的過程2. ASP中常用的22個FSO文件操作函數整理3. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執行過程解析4. SharePoint Server 2019新特性介紹5. .Net core 的熱插拔機制的深入探索及卸載問題求救指南6. 解決ASP中http狀態跳轉返回錯誤頁的問題7. 讀大數據量的XML文件的讀取問題8. ASP編碼必備的8條原則9. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁10. ASP調用WebService轉化成JSON數據,附json.min.asp
