Check content before using regex match

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.

Answers


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.


Need Your Help

slideshow inside header.tpl

module header positioning slideshow opencart

I am using Opencart 1.5.3.1 with custom theme.

build android .apk on the server side? what do I need to setup?

android air adobe apk server-side

I'm working on a project that requires me to give users the ability to input some data into a webform and when submitting the data, an .apk will be generated based on the given information for them...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.