soren121
soren121

Reputation: 368

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

The host that the majority of my script'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?

Upvotes: 1

Views: 141

Answers (3)

tish
tish

Reputation: 1

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.

Upvotes: 0

epascarello
epascarello

Reputation: 207527

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?

Upvotes: 1

Sampson
Sampson

Reputation: 268424

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.

Upvotes: 0

Related Questions