js去掉字符串前后空格的五種方法
第一種:循環(huán)檢查替換
//供使用者調(diào)用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內(nèi)部實現(xiàn)為:[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. php測試程序運行速度和頁面執(zhí)行速度的代碼2. ASP中常用的22個FSO文件操作函數(shù)整理3. 三個不常見的 HTML5 實用新特性簡介4. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析5. ASP調(diào)用WebService轉化成JSON數(shù)據(jù),附json.min.asp6. SharePoint Server 2019新特性介紹7. React+umi+typeScript創(chuàng)建項目的過程8. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析10. php網(wǎng)絡安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究
