开发者

Escape quotes inside certain html elements with regexp?

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:

开发者_JAVA技巧
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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜