'Googlescript - Regex test null before error

I wrote a google script function with regex to retrieve information from a web page. I get 10 information per page with 10 different regex, but the problem is that when an information is not present I have an error for the corresponding regex. RegularExp "TypeError: Cannot read property '1' of null.

I tried to do a test to avoid this error but as soon as the regex pattern doesn't find anything, it returns this error. I can't test before the error.

Translated with www.DeepL.com/Translator (free version)

if (typeof(regExp.exec(html)[1]) === "null") {
var lastName = "error";
}else {
var lastName = regExp.exec(html)[1];
}
  • Do you know how to test before Regex error and indicate the value is false or empty ?

Thanks



Solution 1:[1]

The value in your var html is null, and you are trying to access the null value which has no properties. This causes the error "TypeError: Cannot read property '1' of null".

To fix this, add an if statement where it will check if regExp.exec(html) has value then add your if-else statement.

Your code should look like this:

  if(regExp.exec(html){
    if (typeof(regExp.exec(html)[1]) === "null"){
    var lastName = "error";
    }else {
    var lastName = regExp.exec(html)[1];
    }
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1