TypeError:无法读取属性' 1' of null theFunction [Javascript]

时间:2017-11-21 22:08:27

标签: javascript typeerror

我有一段像这样的javascript代码:

var regex = /<img.*?src=['"](.*?)['"]/;
var image = regex.exec(input.str)[1]; 

并且在执行正则表达式时没有找到任何内容时会出现错误。

TypeError: Cannot read property '1' of null theFunction (eval at <anonymous> (/var/task/index.js:52:23), <anonymous>:50:34) eval (eval at <anonymous> (/var/task/index.js:52:23), <anonymous>:68:20) Domain.<anonymous> (/var/task/index.js:53:5) Domain.run (domain.js:228:14) module.exports.handler (/var/task/index.js:51:5)

有没有办法阻止此错误发生?

1 个答案:

答案 0 :(得分:0)

我只是检查它是否为空。

var regex = /regex/;
var executedReg = regex.exec(input.str);

if (executedReg != null) {
    let image = executedReg[1];
}