1

In the code below, I want to edit it so that it strips out the first line.

function update(url,cln){
    $.ajax({
        url: url,
        dataType: "HTML",
        error: function(msg){
            alert(msg.statusText);
            return msg;
        },
        success: function(html){
            $("#main").html(html + '<a id="MAX"></a>');
        }
    });
}

For example if the code contacts the url: http://stackoverflow.com/
The url returns:

<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<div id="data">
    <div id="test">
    </div>
</div>

It would strip out the first line so that when it writes the html to the #main it would only write:

<div id="data">
    <div id="test">
    </div>
</div>
Ryflex
  • 5,559
  • 25
  • 79
  • 148

3 Answers3

4

You can use a regular expression that matches everything from the beginning of the string up to the first line break:

html = html.replace(/^.*?\r?\n/, '');

Demo: http://jsfiddle.net/Guffa/7pdqw/

Explanation of the regular expression:

^    - matches the beginning of the string
.*?  - matches zero or more character, non-greedy
\r?  - matches zero or one carriage return character
\n   - matches a line feed character
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • I put that regex into regex101 to try and work out how it works but their description isn't making any sense, eRIZ in my comments posted a link using `.splice(0,1);` which way is better, splice or a regex? Is there any advantages or disadvantages to either? – Ryflex Dec 02 '13 at 22:41
  • 1
    @Hyflex: I added an explanation of the regular expression above. Splitting the string up into an array and the join it back together is not an efficient way to remove part of a string. If you want to use something other than a regular expression, you should use string operations to find the line break and get the rest of the string, i.e. `html = html.substr(html.indexOf('\n'));`. – Guffa Dec 03 '13 at 00:04
2

The following will select the part of the content you need

function update(url,cln){
    $.ajax({
        url: url,
        dataType: "HTML",
        error: function(msg){
            alert(msg.statusText);
            return msg;
        },
        success: function(html){
            $("#main").html($(html).find('#data').html() + '<a id="MAX"></a>');
        }
    });
}
Jonathan de M.
  • 9,721
  • 8
  • 47
  • 72
0

You should use .filter() or .load(). http://api.jquery.com/load

How do I filter the returned data from jQuery.ajax?

Community
  • 1
  • 1
loveNoHate
  • 1,549
  • 13
  • 21
  • What is the major differences over using .filter or .load over .html, all three would work wouldn't they? – Ryflex Dec 02 '13 at 23:03
  • @Hyflex Actually you need `.html()` AND `.find()` or `.filter()` to have the same functionality as `.load()`. – loveNoHate Dec 02 '13 at 23:06