Check if .match() result is not empty

Viewed 159

I run this regex .match():

var pattern = /property="og:description"\scontent="(.+?)"/;   
var matches = data.match(pattern);
    
if (matches[1]) {
   var = description = matches[1];
}

But occasionally, I get this error:

Uncaught TypeError: matches is null

What can I do to check if matches[1] is not empty?

What I've tried so far

I tried this:

if (matches && matches[1]) {

And

if (matches.length && matches[1].length) {

And

if (matches[1] != null) {

And

if (matches[1] != undefined && matches[1] != null) {

Still getting this error occasionally. Clearly I'm missing something.

1 Answers

Remove the [1] from matches when you check it has a value. The error is because you're trying to access a null value by index.

let pattern = /property="og:description"\scontent="(.+?)"/;   

['foobar', 'property="og:description" content="abc"'].forEach(data => {
   let matches = data.match(pattern);
   let description = 'no match';
   if (matches) 
    description = matches[1];
    
   console.log(description);   
});

Related