+1 vote
in Other by
I am getting output from a FB page notes using the Facebook API. In some notes there is an image and in others there are not. I want to extract the src of the image if it is there.

I am using this regex and it works fine, but the problem is that if a note does not contain an image all fails.

json.data[i].message.match(/src=(.+?[\.jpg|\.gif|\.png]")/)[1]

Can I use some kind of a control structure (if else) to check if a note contains an image before using the regex?

If the note does not contain an image I get this error:

Result of expression 'json.data[i].message.match(/src=(.+?[\\.jpg|\\.gif|\\.png]\")/)' [null] is not an object.

I am using Javascript and Appcelerator.

JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by
Can I use some kind of a control structure (if else) to check if a note contains an image before using the regex?

Yes to the control structure, but you don't need to do it before the regex, the regex tells you whether it's successful. Break your statement into two parts:

var result = json.data[i].message.match(/src=(.+?[\.jpg|\.gif|\.png]")/);

if (result) {

    path = result[1];

}

The problem you're having is that match returns null when there's no match, but then you're trying to treat it like an object by applying [1] to it — causing an error. By getting the result and making sure it's not falsey (as above), you're only using [1] if the result is not null.
...