2014-01-29 45 views
10

我想創建一個String方法,該方法接受RegExp和回調,然後通過RegExp分割String,並在split中插入回調的返回值陣列。總之,它會做這樣的事情:爲什麼語句if(!condition){console.log(condition)}顯示爲真

"a 1 b 2 c".method(/\d/, function ($1) { return $1 + 1; }) 
    => [a, 2, b, 3, c] 

如果字符串不匹配正則表達式,它應該返回一個數組,像這樣:

"a b c d e".method(/\d/, function ($1) { return $1 + 1; }) 
    => ["a b c d e"] 

我寫了這個代碼,但

String.prototype.preserveSplitReg = function(reg, func) { 

    var rtn = [], 
     that = this.toString(); 
    if (!reg.test(that)) { 
     console.log(reg, that, reg.test(that)); 
     return [that]; 
    } 

    ... 
} 

的執行console.log應該被稱爲只有當字符串不匹配reg,右:因爲我認爲它不工作?但有時它會記錄(reg, that, true)。麻煩的String和reg分別是:

"See <url>http://www.w3.org/TR/html5-diff/</url> for changed elements and attributes, as well as obsolete elements and" 
/<url>.*?<\/url>/g 

控制檯日誌爲true。我無法弄清楚爲什麼。任何幫助將不勝感激。

+0

你能使用這個小提琴複製嗎? http://jsfiddle.net/QN8MT/ – jacquard

+0

thecoder:我不喜歡小提琴。修改了你的建議,看起來像在工作...... – kipenzam

+0

Felix:很有趣。我已經注意到\ d和[0-9]之間的細微差別, – kipenzam

回答

相關問題