0

I am using the following code in Google app script to extract a number.

function getBTC_ZAR_ExchangeRate() {
  var response = UrlFetchApp.fetch("http://coinmill.com/rss/BTC_ZAR.xml")
  var xmlText = response.getContentText();
  //var funded = Xml.parse(htmlText, true);
  var rate = xmlText.match(/BTC =\s(.*?)\sZAR<br/);    
  return rate[1];
}

I get an array with two items as a result. Only the second item in the array is the correct one.

result = {"BTC = 27.45 ZAR<br", "27.45"}

What am I doing wrong, because this cannot be the way it is suppose to work?

Rynardt
  • 5,547
  • 7
  • 31
  • 43

2 Answers2

2

This is the expected behavior. See the first example on MDN. The values returned from match are 1. the pattern that you matched (you told it to match that whole thing, so it did; 2. followed by the value(s) from that pattern matched (in your case 27.45).

Phil Bozak
  • 2,792
  • 1
  • 19
  • 27
  • So is there a correct way of only getting the one correct answer I want? – Rynardt Feb 27 '13 at 13:52
  • [You can read about a similar quesetion here](http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regex). All solutions I have seen involve getting the second element. You can safely assume that `[1]` will not return an error if there is a match. – Phil Bozak Feb 27 '13 at 14:08
0

As Phil Bozak answered, this is how match works. But this is a JavaScript function and has nothing to do otherwise with Google Apps Script specifically.

sjsyrek
  • 193
  • 1
  • 8