开发者

JS: How do I strip unwanted code from the end of a string?

The host that the majority of my scrip开发者_开发技巧t's users are on forces an text ad at the end of every page. This code is sneaking into my script's AJAX responses. It's an HTML comment, followed by a link to their signup page. How can I strip this comment and link from the end of my AJAX responses?


Typically those scripts basically look for text/html content and just shove the code into the stream. Have you tried setting the content type to something else such as text/json, text/javascript, text/plain and see if it gets by without the injection?


Regular Expressions

My first suggestion would be to find a regular expression that can match and eliminate that trailing information. I'm not the greatest at writing regular expressions but here's an attempt:

var response = "I am the data you want. <strong>And nothing more</strong> <!-- haha -> <a href='google.com'>Sucker!</a>";
var myStuff = response.replace("/\s+?<!--.*>$/gi", "");

Custom Explosion String

What would be an easy and quick solution would be to place a string at the end of your message ("spl0de!"), and then split the ajax response on that, and only handle that which comes before it.

var myStuff = response.split("spl0de!")[0];

This would remove anything anybody else sneaks onto the end of your data.


you see a lot of this with hand-generated xml, it isn't valid , so consumers try to fix-up the broken xml with hand-rolled regex -- its completely the wrong approach. you need to fix this at the source, at the broken host.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜