// 類似C#裏的Trim String.prototype.Trim = function(mode) { var re; var str = this; switch(parseInt(mode)) { case 1: //去除左邊空白 re = /^/s*/g; break; case 2: //去除右邊空白 re = //s*$/g; break; case 3: //修剪中間多餘空白,去除左右空白 str = str.replace(//s+/g,' '); re = /(^/s*)|(/s*$)/g; break; case 4: //去除所有空白 re = //s+/g; break; default: //去除左右空白 re = /(^/s*)|(/s*$)/g; break; } return str.replace(re,''); } // 截取前幾個字符,並制定省略符號 String.prototype.Left = function(precision, more) { var str = this; if(!more) more = ''; if(str.length > precision) return str.substr(0, precision-more.length) + more; else return str; } // 判斷字符串是否爲整數 String.prototype.IsInt = function() { var Int = parseInt(this,10); if(isNaN(Int)) return false; if(Int.toString() != this) return false; return true; } // 判斷字符串是否爲浮點數 String.prototype.IsFloat = function() { var Float = parseFloat(this,10); if(isNaN(Float)) return false; if(Float.toString() != this) return false; return true; } // 指定精度並四捨五入 String.prototype.Round = function(precision) { var R = Math.pow(10, precision); return Math.round(this * R) / R; } // 指定精度並四捨五入(重載,適應其它類型) Object.prototype.Round = function(precision) { var R = Math.pow(10, precision); return Math.round(this * R) / R; }
在Javascript中對String的一些方法擴展,實現常用的字符串處理。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.