I have some JavaScript that should be getting this image URL[1] from an XML document with the following code. However Chrome’s console returns Uncaught TypeError: Cannot read property '1' of null on this line. Is the regex incorrect?
var image = $(post.description.match(/<br\/>(<a.*><img.*<\/a>)<br\/>/)[1]).addClass('photo');
[1] http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/391316_483838581645230_1080523933_s.jpg
The XML is structured like so:
<description>
<![CDATA[
Extendemos una cordial felicitación a Reserva de la Biosfera Banco Chinchorro que celebra su aniversario el día de hoy.
Un especial saludo a Maricarmen García, Directora de la Reserva y Líder 2010 del Programa de Liderazgo. ¡Estamos muy
orgullosos de su trabajo!<br /> <br /> We would like to co
]]>
<![CDATA[
ngratulate Banco Chinchorro Biosphere Reserve who is celebrating their anniversary today. A special greeting to Maricarmen
García, the Reserve's Director and 2010 MAR Leadership Fellow. We are so proud of your work!<br /> <br />
<a href="http://pyucatan.conanp.gob.mx/chincho.htm" target="_blank" rel="nofollow nofollow"
onmousedown="UntrustedLink.bootstrap($(this), "HAQE2sh3f", event, bagof({}));">http://pyucatan.conanp.gob.mx/chincho.htm</a><br/><br/>
<a href="http://www.facebook.com/photo.php?fbid=483838581645230&set=a.167790786583346.41662.123942950968130&type=1&relevant_count=1"
title="" target=""><img class="img" src="http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/391316_483838581645230_1080523933_s.jpg" alt="" /></a>
]]>
</description>
Yes.
/<br\/>(<a.*><img.*<\/a>)<br\/>/tries to match br-tags without a space, and also in the string you gave us there is no<br>after the link. So, the match returnsnulland has no property “1“.Anyway, Regex is not suited for this task. Just get the
textContentof your<description>node, parse it as HTML with jQuery (see Can jQuery Parse HTML Stored in a Variable?), or even as X[HT]ML withjQuery.parseXML, and use a selector to get thea > imgelement out of it, in order to read thesrcattribute.