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;}
轉(zhuǎn)自:http://www.2cto.com/kf/201204/125943.html
相關(guān)文章:
1. vue組件庫的在線主題編輯器的實現(xiàn)思路2. 如何用 Python 制作一個迷宮游戲3. 部署vue+Springboot前后端分離項目的步驟實現(xiàn)4. Django如何使用asyncio協(xié)程和ThreadPoolExecutor多線程5. AspNetCore&MassTransit Courier實現(xiàn)分布式事務(wù)的詳細過程6. idea設(shè)置自動導(dǎo)入依賴的方法步驟7. 網(wǎng)頁中img圖片使用css實現(xiàn)等比例自動縮放不變形(代碼已測試)8. Python安裝并操作redis實現(xiàn)流程詳解9. ASP常用日期格式化函數(shù) FormatDate()10. JavaScript實現(xiàn)組件化和模塊化方法詳解
