1

I tend to use the image solution described by 24Ways to use ajax and scripts.

However, The ajax results are out of my control and I need a regexp to escape the quotes (' and ") since the scripts will house in an onload attribute.

This is my work so far:

clean_txt = clean_txt.replace(
    /<script[^>]*>([\n\s\S]+?)<\/script>/img, 
    "<img src='1px.gif?d=$1' alt='' onload='new Function(\"$1\")();' />"
);

Does anyone have the final regexp, e g to escape the quotes in $1?

Andy E
  • 338,112
  • 86
  • 474
  • 445
madr
  • 655
  • 4
  • 16

2 Answers2

0

Parsing html with regex will destroy your soul.

I'd really suggest using something simpler like:

clean_txt.replace("'","\\'").replace('"', '\\"');

Of course, this will replace every ' with \' and " with \". If you don't want that, read more about XML parsing in Javascript.

Community
  • 1
  • 1
darioo
  • 46,442
  • 10
  • 75
  • 103
  • Unfortunately, the results I'm getting are not reliable enough to be evaluated as XML. But thanks anyway. – madr Dec 13 '10 at 14:15
  • This will not replace every quote. It will only replace the first of each quote type. `'aaa'.replace('a', 'b') === 'baa'`. You need to use regexp replace : `'aaa'.replace(/a/g, 'b') === 'bbb'`, and probably replace them with HTML entities instead of back-slash escape. – Mike Samuel Dec 13 '10 at 14:59
0

Turns out it could be solved by escaping the wrapper quotes on the onload function.

clean_txt = clean_txt.replace(/<script[^>]*>([\n\s\S]+?)<\/script>/img, 
            "<img src='1px.gif?d=$1' alt='' onload=\'$1\;\' />");

A bit ugly and weird, but I can live with that. By doing this, browsers seems to walk around the problem theirselves.

I have tested in Opera 10.6, Firefox 3.6, Safari 5 and Chrome 7.

madr
  • 655
  • 4
  • 16