0

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&#039;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), &quot;HAQE2sh3f&quot;, event, bagof({}));">http://pyucatan.conanp.gob.mx/chincho.htm</a><br/><br/>
<a href="http://www.facebook.com/photo.php?fbid=483838581645230&amp;set=a.167790786583346.41662.123942950968130&amp;type=1&amp;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>
Zamani
  • 306
  • 3
  • 15
Simpleton
  • 6,285
  • 11
  • 53
  • 87

2 Answers2

2

Is the regex incorrect?

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 returns null and has no property "1".

Anyway, Regex is not suited for this task. Just get the textContent of your <description> node, parse it as HTML with jQuery (see Can jQuery Parse HTML Stored in a Variable?), or even as X[HT]ML with jQuery.parseXML, and use a selector to get the a > img element out of it, in order to read the src attribute.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Regex is a big no-no for parsing HTML/XML.

You should try parsing with jQuery.parseXML()

Community
  • 1
  • 1
Robin Maben
  • 22,194
  • 16
  • 64
  • 99