0
<span class="locationtitle">
    <a href="#">Test Text</a><br>
    6:00 p.m. - 12:00 a.m.<br>
    Repeat on the first Thursday
</span>

I am trying to come up with a way with jQuery to remove the last sentence. So everything after the 2nd <br>. The text in that sentence potentially could be anything so doing a find() won't work.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Mark K
  • 581
  • 1
  • 3
  • 13

2 Answers2

6

You could do this :

$('.locationtitle').html(function(_,html) { 
    return html.split(/<br\s*\/?>/i).slice(0,-1).join('<br>')
});

This supports other ways to write the <br>, for example <BR/>, you could use 

Some explanation :

  • jQuery's html callback takes two arguments, I don't need the first one (the index)
  • split makes an array from a string, using the <br> (or its variants) as separator
  • slice returns a copy of the array without the last element
  • join makes a string back from the array, inserting the needed <br>
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

Assuming that last sentence doesn't contain any HTML, a mixture of vanilla JS and jQuery may work best here:

var s = $('.locationtitle')[0].childNodes; // HTML and text nodes
var last = s[s.length-1];                  // selects the last node
$(last).wrap('<span>').parent().hide();    // can only hide HTML elements

http://jsfiddle.net/mblase75/NXZpL/

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • Doesn't work if you add other elements. See the example I gave to the other wrong answer. – Denys Séguret May 06 '13 at 18:20
  • Much like Mohammad Adil's answer, this only removes the last node, rather than everything after the last
    tag as the OP requested.
    – Maple May 06 '13 at 18:21