无法访问JS Regex结果 - 无法读取属性' 1'为null

时间:2017-09-05 21:01:04

标签: javascript regex

我有一些代码,我从页面抓取网址,然后使用正则表达式获取两个字符串之间的文本。当我这样做时,我得到了我想要的匹配但我无法访问结果。

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:无法读取属性' 1' null。

1 个答案:

答案 0 :(得分: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);
相关问题