我有一些代码,我从页面中抓取 URL,然后使用正则表达式获取两个字符串之间的文本。当我这样做时,我得到了我想要的匹配,但我无法访问结果。
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.
最佳答案
您似乎已经对数组中的所有元素进行了此操作评估
。我的猜测是,其中一个元素不匹配,并且会引发错误,因为在这种情况下,match
将返回 null
。
最好先将match
的结果存储在变量中。这样,您可以在访问它的 [1]
之前检查它是否为 null
:
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);
关于javascript - 无法访问 JS 正则表达式结果 - 无法读取 null 的属性 '1',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46063295/