2017-09-05 36 views
2

我有一些代碼,我從一個頁面抓取URL,然後使用正則表達式來獲取兩個字符串之間的文本。當我這樣做時,我得到了我想要的比賽,但我無法獲得結果。無法訪問JS正則表達式結果 - 無法讀取null的屬性'1'

evaluated.forEach(function(element) { 
    console.log(element.match(/.com\/(.*?)\?fref/)[1]); 
}, this); 

如果我刪除[1],我在控制檯看到的結果爲:

[ 
    '.com/jkahan?fref', 
    'jkahan', 
    index: 20, 
    input: 'https://www.example.com/jkahan?fref=pb&hc_location=friends_tab' 
] 

但是,當我加入[1]訪問我想要的結果,我得到:

TypeError: Cannot read property '1' of null.

回答

3

你似乎已經完成了陣列中的所有元素evaluated。我的猜測是其中一個元素不匹配,並且會拋出錯誤,因爲在這種情況下,match將返回null

最好先將變量match的結果保存在變量中。這樣一來,你可以檢查它是否null或不訪問它[1]前:

evaluated.forEach(function(element) { 
    var result = element.match(/.com\/(.*?)\?fref/); // store the result of 'match' in the variable 'result' 
    if(result)          // if there is a result (if 'result' is not 'null') 
     console.log(result[1]);      // then you can access it's [1] element 
}, this); 
+0

這是奇怪的。在使用相同的if語句之前,我嘗試了類似的東西。不知怎的,我一定會搞砸了。這工作。謝謝。 – xendi

+0

不客氣!您可能忘記在'if'前面的行中刪除'[1]'。 –