Reputation:
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
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
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
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
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