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?

2

2 Answers 2

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.

2
  • Unfortunately, the results I'm getting are not reliable enough to be evaluated as XML. But thanks anyway.
    – madr
    Dec 13, 2010 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. Dec 13, 2010 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.