添加到String.prototype中的方法比較多,不過歸結起來,大致分為下面幾類:
| 分類 |
方法名 |
| 原始能力增強 |
strip | include | startsWith | endsWith | empty | blank |
| 格式 |
camelize | capitalize | underscore | dasherize | inspect |
| 變形 |
toArray | succ | times |
| 替換 |
interpolate | sub | scan | truncate | gsub |
| HTML處理 |
stripTags | escapeHTML | unescapeHTML |
| 參數序列化 |
toQueryParams |
| JSON處理 |
unfilterJSON | isJSON | evalJSON | parseJSON |
| 指令碼處理 |
stripScripts | extractScripts | evalScripts |
從基本的原始能力增強開始,下面是具體的實現,這一段很好理解的:
複製代碼 代碼如下:(function(s){
function strip(){
return this.replace(/^\s+/,'').replace(/\s+$/,'');
}
function include(pattern){
return this.indexOf(pattern) > -1;//split
}
function startsWith(pattern) {
return this.lastIndexOf(pattern, 0) === 0;
}
function endsWith(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.indexOf(pattern, d) === d;
}
function empty() {
return this == '';
}
function blank() {
return /^\s*$/.test(this);
}
s.strip = String.prototype.trim || strip;
s.include = include;
s.startsWith = startsWith;
s.endsWith = endsWith;
s.empty = empty;
s.blank = blank;
})(String.prototype);
上面的strip在jquery裡面是$.trim,而且大部分貌似都是trim。這裡直接擴充原生原型的悲劇之處就顯現出來了,因為後面的JS實現中(比如chrome)就實現了trim方法,那就弄巧成拙了。 複製代碼 代碼如下:function strip(){
return this.replace(/^\s+/,'').replace(/\s+$/,'');
}
這裡面的replace(/^\s+/,'')就是trimLeft,replace(/\s+$/,'')是trimRight,不過Prototype.String中沒有這兩個方法。
下面是這一部分比較有意思的地方:
當時看這段的時候,對其中的startsWith和endsWith甚是不解,按理來說,startsWith用indexOf就可以了,這裡卻是用的lastIndexOf。後來去翻了一下Prototype1.6版本的實現: 複製代碼 代碼如下:function startsWith(pattern) {
return this.indexOf(pattern) === 0;
}
function endsWith(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
}
可見,以前版本中startsWith用的就是indexOf,不過1.7版本修改了startsWith的實現。在1.7版本中:
startsWith實現中lastIndexOf從後向前尋找,不過起點(fromindex)設定為0,因此,只需要檢測開頭一次就可以了。
endsWith實現中indexOf從前向後尋找,由於字串長度不定,因此這裡計算了一下長度,然後再確定了起點(fromindex),因此也只需要檢測結尾一次就可以了。
這裡的效能最佳化之處在於,1.6的實現中,如果開頭沒有匹配(就是startsWith不成立),但是indexOf依舊會向後尋找,直到找到一個匹配的或者字串結尾,這樣就浪費了。舉個例子,對於下面的一個操作:
'abcdefgabcdefg'.startsWith('abc')
在1.6版本和1.7版本的實現中,沒有任何區別,但是我們轉換一下:
'abcdefgabcdefg'.startsWith('xesam')
在1.6實現中,startsWith內部的indexOf操作會在開頭的a沒有和x匹配後,雖然沒有必要再繼續了,但是indexOf依舊會繼續向後尋找,直到找到匹配的‘xesam'或者字串末尾。
在1.7實現中,startsWith內部的lastIndexOf是反向尋找的(fromIndex=0),因此在開頭的a沒有和x匹配後,操作就停止了,因為lastIndexOf已經到頭了。
這麼一對比,如果待檢測的字串非常長的話,兩種實現方式的效率會有明顯的區別。
endsWith的原理也是一樣的。