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)部實(shí)現(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. 基于android studio的layout的xml文件的創(chuàng)建方式2. 詳解Android studio 動(dòng)態(tài)fragment的用法3. 圖文詳解vue中proto文件的函數(shù)調(diào)用4. 解決Android studio xml界面無法預(yù)覽問題5. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)6. 什么是python的自省7. Android如何加載Base64編碼格式圖片8. 使用Android studio查看Kotlin的字節(jié)碼教程9. Vuex localStorage的具體使用10. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)

網(wǎng)公網(wǎng)安備