user10498292
user10498292

Reputation:

How to get false when match finds nothing?

When I run this code:

var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = foundUrlString[1];

I get an error if there are no matches on the page:

Result of expression 'foundUrlString' [null] is not an object

How can I get "false" when there are no matches instead of this error?

Upvotes: 1

Views: 67

Answers (4)

Ele
Ele

Reputation: 33726

You need to understand what's the purpose of String.prototype.match. The function match will return an array with the whole set of matched groups in your regexp. So, if you want to validate a string, the best way is using the function RegExp.prototype.test.

Use the function RegExp.prototype.test from regexp:

let savedPage = "EleFromStack";
console.log(/og:url.*="(http.*\.com)/i.test(savedPage));

Upvotes: 0

ferhado
ferhado

Reputation: 2594

Here is an example with try and catch which may help you:

function regex(savedPage) {
  try {
    var foundUrlString = savedPage.match(/og:url.*="(http.*\.com)/i);
    return foundUrlString[1];
  } catch (error) {
    return false;
  }
}
var savedPage1 = '<link property="og:url" content="http://test.com/test">';
console.log('savedPage1',regex(savedPage1));
var savedPage2 = '<link content="http://test.com/test">';
console.log('savedPage2',regex(savedPage2));

Upvotes: 0

spencer.sm
spencer.sm

Reputation: 20526

Going off of what you have, you could add a "truthy" check on the second line:

var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = !!foundUrlString && foundUrlString[1];

That will leave foundUrl either as a matched string or false.

Upvotes: 1

Dhana
Dhana

Reputation: 1658

Check null to print false or true.

        var savedPage = '';
        var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
        var foundUrl = foundUrlString == null ? false : true;
        console.log(foundUrl );

Upvotes: 0

Related Questions