views:

22

answers:

2

The Backstory:

This works fine in all browsers EXCEPT Safair (5.0.1)

var chunk = arr[i];
chunk = chunk.replace('$', '\\$');
var a = eval('message.match(/' + chunk + '/gi);');
if(a instanceof Array) symbol = symbol.concat(a);

So I modified it to the following:

var chunk = String(arr[i]);
chunk = chunk.replace('$', '\\$');
var a = eval('message.match(/' + chunk + '/gi);');
if(a instanceof Array) symbol = symbol.concat(a);

Which made Safari a BIT more happy to where it was just throwing an ambiguous error (FUN!)

I've found the solution and I'm posting it below in case any other fellow scripters run into this problem.

A: 

So- I put a try/catch around the problem area (naturally) to try and get some sort of feedback on the error. Funny enough, I get no error and the problem goes away. Weird.

Solution for the slow:

try {
  var chunk = String(arr[i]);
  chunk = chunk.replace('$', '\\$');
  var a = eval('message.match(/' + chunk + '/gi);');
  if(a instanceof Array) symbol = symbol.concat(a);
} catch(e) {}
Jackson
+2  A: 

I couldn't reproduce the problem because I'm not sure what's the value of chunk.

Anyway, this is one more example of an unnecessary usage of eval, you can use the RegExp constructor to build a RegExp object from a string, for example:

var re = /foo/gi;

Is equivalent to creating an object in runtime with the RegExp constructor:

var re = new RegExp('foo', 'gi');

Applying it to your code:

var chunk = String(arr[i]); // use String() only if you are not sure if arr[i] is

// Be aware that the following line is replacing only the first $ 
// char and you may want to scape other meta-characters:
chunk = chunk.replace('$', '\\$');
var a = message.match(new RegExp(chunk,'gi'));

if(a instanceof Array) symbol = symbol.concat(a);
CMS
+1 That struck me as weird too, but I was too lazy to get into it with him.
Robusto