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
CodePudding user response:
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];
}
}
CodePudding user response:
Thanks Nikko, i have modified a little your answer and it's ok for one formula. But, there is the same problem with multi formula on regExp2.
if(regExp1.exec(html)){
if (typeof(regExp1.exec(html)[1]) === "null"){
var lastName = "error";
}else {
var lastName = regExp1.exec(html)[1];
}
}
if(regExp2.exec(html)){
if (typeof(regExp2.exec(html)[1]) === "null"){
var lastName = "error";
}else {
var lastName = regExp2.exec(html)[1];
}
}
if(regExp3.exec(html)){
if (typeof(regExp3.exec(html)[1]) === "null"){
var lastName = "error";
}else {
var lastName = regExp3.exec(html)[1];
}
}
Finally i have use try/catch
try {
var lastName7 = regExp7.exec(html)[1];
}
catch(err) {
var lastName7 ="error";
}
Logger.log(lastName7);
try {
var lastName8 = regExp8.exec(html)[1];
}
catch(err) {
var lastName8 ="error";
}
Logger.log(lastName8);
try {
var lastName9 = regExp9.exec(html)[1];
}
catch(err) {
var lastName9 ="error";
}
Logger.log(lastName9);